CONTENTS

Chapter 9. Security

When Java technology first appeared on the scene, the excitement was not about a well-crafted programming language but about the possibility of safely executing applets that are delivered over the Internet (see Chapter 10 of Volume 1 for more information about applets). Obviously, delivering executable applets is practical only when the recipients are sure that the code can't wreak havoc on their machines. For this reason, security was and is a major concern of both the designers and the users of Java technology. This means that unlike the case with other languages and systems where security was implemented as an afterthought or a reaction to break-ins, security mechanisms are an integral part of Java technology.

Three mechanisms in Java technology help ensure safety:

The Java virtual machine checks for bad pointers, invalid array offsets, and so on. The other steps require controlling what goes to the Java virtual machine.

When class files are loaded into the virtual machine, they are checked for integrity. We show you in detail how that process works. More importantly, we show you how to control what goes to the virtual machine by building your own class loader.

For maximum security, both the default mechanism for loading a class and a custom class loader need to work with a security manager class that controls what actions code can perform. You'll see how to write your own security manager class.

Finally, you'll see the cryptographic algorithms supplied in the java.security package, which allow for code signing and user authentication.

As always, we focus on those topics that are of greatest interest to application programmers. For an in-depth view, we recommend the book Inside Java 2 Platform Security by Li Gong [Addison-Wesley 1999].

Class Loaders

A Java programming language compiler converts source into the machine language of a hypothetical machine, called the virtual machine. The virtual machine code is stored in a class file with a .class extension. Class files contain the code for all the methods of one class. These class files need to be interpreted by a program that can translate the instruction set of the virtual machine into the machine language of the target machine.

Note that the virtual machine interpreter loads only those class files that are needed for the execution of a program. For example, suppose program execution starts with MyProgram.class. Here are the steps that the virtual machine carries out.

  1. The virtual machine has a mechanism for loading class files, for example, by reading the files from disk or by requesting them from the Web; it uses this mechanism to load the contents of the MyProgram class file.

  2. If the MyProgram class has instance variables or superclasses of another class type, these class files are loaded as well. (The process of loading all the classes that a given class depends on is called resolving the class.)

  3. The virtual machine then executes the main method in MyProgram (which is static, so no instance of a class needs to be created).

  4. If the main method or a method that main calls requires additional classes, these are loaded next.

The class loading mechanism doesn't just use a single class loader, however. Every Java program has at least three class loaders:

The bootstrap class loader loads the system classes (typically, from the JAR file rt.jar). It is an integral part of the virtual machine, and is usually implemented in C. There is no ClassLoader object corresponding to the bootstrap class loader. For example,

String.class.getClassLoader()

returns null.

The extension class loader loads a standard extension from the jre/lib/ext directory. You can drop JAR files into that directory, and the extension class loader will find the classes in them, even without any class path. (Some people recommend this mechanism to avoid the "class path from hell," but see the pitfall later in this section.) The extension class loader is implemented in Java.

The system class loader loads the application classes. It locates classes in the directories and JAR/ZIP files on the class path, as set by the CLASSPATH environment variable or the -classpath command-line option. This class loader is also implemented in Java.

Class loaders have a parent/child relationship. Every class loader except for the bootstrap class loader has a parent class loader. A class loader is supposed to give its parent a chance to load any given class and only load it if the parent has failed. For example, when the system class loader is asked to load a system class (say, java.util.ArrayList), then it first asks the extension class loader. That class loader first asks the bootstrap class loader. The bootstrap class loader finds and loads the class in rt.jar, and neither of the other class loaders searches any further.

NOTE

graphics/note.gif
 

It is entirely possible to implement a class loader that doesn't delegate class loading to its parent first. Such a class loader can even load its own version of system classes. However, there seems no benefit to such an arrangement. There is no security risk either—a class can load new code with a class loader, but it can't change its own class loader.

Applets, servlets, and RMI stubs are loaded with custom class loaders. You can even write your own class loader for specialized purposes. That lets you carry out specialized security checks before you pass the bytecodes to the virtual machine. For example, you can write a class loader that can refuse to load a class that has not been marked as "paid for." The next section shows you how.

Given a class loader, you load a new class as follows:

ClassLoader loader = new MyClassLoader();
String className = ". . .";
Class cl = loader.loadClass(className);

Then that class loads other classes on which it depends.

With all these class loaders, you may wonder which one is in charge. Recall again when classes are loaded:

  1. Implicitly, when a class is resolved, that is, when the classes on which it depends are loaded;

  2. Explicitly, but without a named class loader, by calling Class.forName(className);

  3. Through a class loader, by calling loader.loadClass(className).

In the first case, the resolution process uses the same class loader as the one that is loading the original class. In the second case, the class loader of the class whose method contains the Class.forName instruction is used. In the third case, the specified class loader is in charge. This is the only way to switch to a new class loader.

CAUTION

graphics/caution.gif
 

You can run into grief if you drop a JAR file into the jre/lib/ext directory and one of its classes calls Class.forName. That call will only use the extension class loader, and not the system class loader, to find the class. In particular, the class path is never used. Keep that in mind before you use the extension directory as a way to minimize your class file hassles.

NOTE

graphics/note.gif
 

That pitfall begs the question of what you should do if you must dynamically load classes in an extension library. You can call the static ClassLoader.getSystemClassLoader method to get the system class loader. However, that may not be the appropriate class loader to use in all circumstances. After all, the extension code may have been called from a class that was loaded with another class loader. To overcome this problem, every thread has a "context class loader," the class loader that is most reasonable to use when executing code in the thread. Call loadClass with that class loader instead of calling Class.forName:

Thread t = Thread.currentThread();
ClassLoader loader = t.getContextClassLoader();
Class cl = loader.loadClass(className);

Conversely, before starting a new thread, you can set the context class loader:

Thread t = new Thread(. . .);
t.setContextClassLoader(myClassLoader);
t.start();

If no context class loader is set, the thread takes the context class loader of the parent thread. The main thread of an application has the system class loader as its context class loader.

CAUTION

graphics/caution.gif
 

There is a second pitfall with dropping JAR files into the jre/lib/ext directory. Sometimes, programmers forget about the files they placed there months ago. Then they scratch their heads when the class loader seems to ignore the class path, when it is actually loading long-forgotten classes from the extension directory.

Every Java programmer knows that package names are used to eliminate name conflicts. There are two classes called Date in the standard library, but of course their real names are java.util.Date and java.sql.Date. The simple name is only a programmer convenience and requires the inclusion of appropriate import statements. In a running program, all class names contain their package name.

It may surprise you, however, that you can have two classes in the same virtual machine that have the same class and package name. A class is determined by its full name and the class loader. This technique is useful when loading code from multiple sources. For example, a browser uses separate instances of the applet class loader class for each web page. This allows the virtual machine to separate classes from different web pages, no matter what they are named.

NOTE

graphics/note.gif
 

This technique has other uses as well, such as "hot deployment" of servlets and Enterprise Java Beans. See http://developer.java.sun.com/developer/TechTips/2000/tt1027.html for more information.

Writing Your Own Class Loader

To write your own class loader, you simply extend the ClassLoader class and override the method.

findClass(String className)

The loadClass method of the ClassLoader superclass takes care of the delegation to the parent and only calls findClass if the class hasn't already been loaded and if the parent class loader was unable to load the class.

NOTE

graphics/note.gif
 

In earlier versions of the SDK, programmers had to override the loadClass method. That is no longer recommended.

Your implementation of this method must:

  1. Load the bytecodes for the class from the local file system or from some other source.

  2. Call the defineClass method of the ClassLoader superclass to present the bytecodes to the virtual machine.

In the program of Example 9-1, we implement a class loader that loads encrypted class files. The program asks the user for the name of the first class to load (that is, the class containing main) and the decryption key. It then uses a special class loader to load the specified class and calls the main method. The class loader decrypts the specified class and all nonsystem classes that are referenced by it. Finally, the program calls the main method of the loaded class (see Figure 9-1).

Figure 9-1. The ClassLoaderTest program

graphics/09fig01.gif
 

For simplicity, we ignore 2,000 years of progress in the field of cryptography and use the venerable Caesar cipher for encrypting the class files.

NOTE

graphics/note.gif
 

David Kahn's wonderful book The Codebreakers [Macmillan, NY, 1967, p. 84] refers to Suetonius as a historical source for the Caesar cipher. Caesar shifted the 24 letters of the Roman alphabet by 3 letters. At the time of this writing, the U.S. government restricts the export of strong encryption methods. Therefore, we use Caesar's method for our example since it is so weak that it is presumably legal for export.

Our version of the Caesar cipher has as a key a number between 1 and 255. To decrypt, simply add that key to every byte and reduce modulo 256. The Caesar.java program of Example 9-2 carries out the encryption.

In order not to confuse the regular class loader, we use a different extension, .caesar, for the encrypted class files.

To decrypt, the class loader simply subtracts the key from every byte. On the CD-ROM for this book, you will find four class files, encrypted with a key value of 3—the traditional choice. You cannot load these classes via the regular bytecode interpreter, but you can run the encrypted program by using the custom class loader defined in our ClassLoaderTest program.

Encrypting class files has a number of practical uses (provided, of course, that you use a cipher stronger than the Caesar cipher). Without the decryption key, the class files are useless. They can neither be executed by a standard bytecode interpreter nor readily disassembled.

This means that you can use a custom class loader to authenticate the user of the class or to ensure that a program has been paid for before it will be allowed to run. Of course, encryption is only one application of a custom class loader. You can use other types of class loaders to solve other problems, for example, storing class files in a database.

Example 9-1 ClassLoaderTest.java
  1. import java.util.*;
  2. import java.io.*;
  3. import java.lang.reflect.*;
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. import javax.swing.*;
  7.
  8. /**
  9.    This program demonstrates a custom class loader that decrypts
 10.    class files.
 11. */
 12. public class ClassLoaderTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new ClassLoaderFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame contains two text fields for the name of the class
 24.    to load and the decryption key.
 25. */
 26. class ClassLoaderFrame extends JFrame
 27. {
 28.    public ClassLoaderFrame()
 29.    {
 30        setTitle("ClassLoaderTest");
 31.       setSize(WIDTH, HEIGHT);
 32.       getContentPane().setLayout(new GridBagLayout());
 33.       GridBagConstraints gbc = new GridBagConstraints();
 34.       gbc.weightx = 0;
 35.       gbc.weighty = 100;
 36.       gbc.fill = GridBagConstraints.NONE;
 37.       gbc.anchor = GridBagConstraints.EAST;
 38.       add(new JLabel("Class"), gbc, 0, 0, 1, 1);
 39.       add(new JLabel("Key"), gbc, 0, 1, 1, 1);
 40.       gbc.weightx = 100;
 41.       gbc.fill = GridBagConstraints.HORIZONTAL;
 42.       gbc.anchor = GridBagConstraints.WEST;
 43.       add(nameField, gbc, 1, 0, 1, 1);
 44.       add(keyField, gbc, 1, 1, 1, 1);
 45.       gbc.fill = GridBagConstraints.NONE;
 46.       gbc.anchor = GridBagConstraints.CENTER;
 47.       JButton loadButton = new JButton("Load");
 48.       add(loadButton, gbc, 0, 2, 2, 1);
 49.       loadButton.addActionListener(new
 50.          ActionListener()
 51.          {
 52.             public void actionPerformed(ActionEvent event)
 53.             {
 54.               runClass(nameField.getText(), keyField.getText());
 55.             }
 56.          });
 57.    }
 58.
 59.    /**
 60.       A convenience method to add a component to given grid bag
 61.       layout locations.
 62.       @param c the component to add
 63.       @param gbc the grid bag constraints to use
 64.       @param x the x grid position
 65.       @param y the y grid position
 66.       @param w the grid width
 67.       @param h the grid height
 68.    */
 69.    public void add(Component c, GridBagConstraints gbc,
 70.       int x, int y, int w, int h)
 71.    {
 72.       gbc.gridx = x;
 73.       gbc.gridy = y;
 74.       gbc.gridwidth = w;
 75.       gbc.gridheight = h;
 76.       getContentPane().add(c, gbc);
 77.    }
 78.
 79.    /**
 80.       Runs the main method of a given class.
 81.       @param name the class name
 82.       @param key the decryption key for the class files
 83.    */
 84.    public void runClass(String name, String key)
 85.    {
 86.       try
 87.       {
 88.          ClassLoader loader
 89.             = new CryptoClassLoader(Integer.parseInt(key));
 90.          Class c = loader.loadClass(name);
 91.          String[] args = new String[] {};
 92.
 93.          Method m = c.getMethod("main",
 94.             new Class[] { args.getClass() });
 95.          m.invoke(null, new Object[] { args });
 96.       }
 97.       catch (Throwable e)
 98.       {
 99.          JOptionPane.showMessageDialog(this, e);
100.       }
101.    }
102.
103.    private JTextField keyField = new JTextField("3", 4);
104.    private JTextField nameField = new JTextField(30);
105.    private static final int WIDTH = 300;
106.    private static final int HEIGHT = 200;
107. }
108.
109. /**
110.    This class loader loads encrypted class files.
111. */
112. class CryptoClassLoader extends ClassLoader
113. {
114.    /**
115.       Constructs a crypto class loader.
116.       @param k the decryption key
117.    */
118.    public CryptoClassLoader(int k)
119.    {
120.       key = k;
121.    }
122.
123.    protected Class findClass(String name)
124.       throws ClassNotFoundException
125.    {
126.       byte[] classBytes = null;
127.       try
128.       {
129.          classBytes = loadClassBytes(name);
130.       }
131.       catch (IOException exception)
132.       {
133.          throw new ClassNotFoundException(name);
134.       }
135.
136.       Class cl = defineClass(name, classBytes,
137.          0, classBytes.length);
138.       if (cl == null)
139.             throw new ClassNotFoundException(name);
140.       return cl;
141.    }
142.
143.    /**
144.       Loads and decrypt the class file bytes.
145.       @param name the class name
146.       @return an array with the class file bytes
147.    */
148.    private byte[] loadClassBytes(String name)
149.       throws IOException
150.    {
151.       String cname = name.replace('.', '/') + ".caesar";
152.       FileInputStream in = null;
153.       try
154.       {
155.          in = new FileInputStream(cname);
156.          ByteArrayOutputStream buffer
157.             = new ByteArrayOutputStream();
158.          int ch;
159.          while ((ch = in.read()) != -1)
160.          {
161.             byte b = (byte)(ch - key);
162.             buffer.write(b);
163.          }
164.          in.close();
165.          return buffer.toByteArray();
166.       }
167.       finally
168.       {
169.          if (in != null)
170.             in.close();
171.       }
172.    }
173.
174.    private Map classes = new HashMap();
175.    private int key;
176. }
Example 9-2 Caesar.java
 1. import java.io.*;
 2.
 3. /**
 4.    Encrypts a file using the Caesar cipher.
 5. */
 6. public class Caesar
 7. {
 8.    public static void main(String[] args)
 9.    {
10.       if (args.length != 3)
11.       {
12.          System.out.println("USAGE: java Caesar in out key");
13.          return;
14.       }
15.
16.       try
17.       {
18.          FileInputStream in = new FileInputStream(args[0]);
19.          FileOutputStream out = new FileOutputStream(args[1]);
20.          int key = Integer.parseInt(args[2]);
21.          int ch;
22.          while ((ch = in.read()) != -1)
23.          {
24.             byte c = (byte)(ch + key);
25.             out.write(c);
26.          }
27.          in.close();
28.          out.close();
29.       }
30.       catch(IOException exception)
31.       {
32.          exception.printStackTrace();
33.       }
34.    }
35. }
java.lang.Class

graphics/api.gif
 

java.lang.ClassLoader

graphics/api.gif
 

java.lang.Thread

graphics/api.gif
 

Bytecode Verification

When a class loader presents the bytecodes of a newly loaded Java platform class to the virtual machine, these bytecodes are first inspected by a verifier. The verifier checks that the instructions cannot perform actions that are obviously damaging. All classes except for system classes are verified. However, you can deactivate verification with the undocumented -noverify option.

For example,

java -noverify Hello

Here are some of the checks that the verifier carries out:

If any of these checks fail, then the class is considered corrupted and will not be loaded.

NOTE

graphics/note.gif
 

If you are familiar with Gödel's theorem, you may wonder how the verifier can prove that a class file is free from type mismatches, uninitialized variables, and stack overflows. Gödel's theorem states that it is impossible to design algorithms whose inputs are program files and whose output is a Boolean value that states whether the input program has a particular property (such as being free from stack overflows). Is this a conflict between the public relations department at Sun Microsystems and the laws of logic? No—in fact, the verifier is not a decision algorithm in the sense of Gödel. If the verifier accepts a program, it is indeed safe. However, there may be many programs that the verifier rejects even though they would actually be safe.

This strict verification is an important security consideration. Accidental errors, such as uninitialized variables, can easily wreak havoc if they are not caught. More importantly, in the wide open world of the Internet, you must be protected against malicious programmers who create evil effects on purpose. For example, by modifying values on the runtime stack or by writing to the private data fields of system objects, a program can break through the security system of a browser.

However, you may wonder why there is a special verifier to check all these features. After all, the compiler would never allow you to generate a class file in which an uninitialized variable is used or in which a private data field is accessed from another class. Indeed, a class file generated by a compiler for the Java programming language always passes verification. However, the bytecode format used in the class files is well documented, and it is an easy matter for someone with some experience in assembly programming and a hex editor to manually produce a class file that contains valid but unsafe instructions for the Java virtual machine. Once again, keep in mind that the verifier is always guarding against maliciously altered class files, not just checking the class files produced by a compiler.

Here's an example of how to construct such an altered class file. We start with the program VerifierTest.java of Example 9-3. This is a simple program that calls a method and displays the method result. The program can be run both as a console program and as an applet. The fun method itself just computes 1 + 2.

static int fun()
{
   int m;
   int n;
   m = 1;
   n = 2;
   int r = m + n;
   return r;
}

As an experiment, try to compile the following modification of this program:

static int fun()
{
   int m = 1;
   int n;
   m = 1;
   m = 2;
   int r = m + n;
   return r;
}

In this case, n is not initialized, and it could have any random value. Of course, the compiler detects that problem and refuses to compile the program. To create a bad class file, we have to work a little harder. First, run the javap program to find out how the compiler translates the fun method. The command

javap -c VerifierTest

shows the bytecodes in the class file in mnemonic form.

Method int fun()
   0 iconst_1
   1 istore_0
   2 iconst_2
   3 istore_1
   4 iload_0
   5 iload_1
   6 iadd
   7 istore_2
   8 iload_2
   9 ireturn

We will use a hex editor to change instruction 3 from istore_1 to istore_0. That is, local variable 0 (which is m) is initialized twice, and local variable 1 (which is n) is not initialized at all. We need to know the hexadecimal values for these instructions. These values are readily available from The Java Virtual Machine Specification by Tim Lindholm and Frank Yellin [Addison-Wesley, 1999].

0 iconst_1 04
1 istore_0 3B
2 iconst_2 05
3 istore_1 3C
4 iload_0  1A
5 iload_1  1B
6 iadd     60
7 istore_2 3D
8 iload_2  1C
9 ireturn  AC

You can use a hex editor (such as Hex Workshop, which you can down-load from http://www.bpsoft.com) to carry out the modification. Or, of course, you can use emacs in hexl-mode. In Figure 9-2, you see the class file VerifierTest.class loaded into Hex Workshop, with the bytecodes of the fun method highlighted.

Figure 9-2. Modifying bytecodes with a hex editor

graphics/09fig02.gif
 

Change 3C to 3B and save the class file. Then try running the VerifierTest program. You get an error message:

Exception in thread "main" java.lang.VerifyError: (class: Verifi-
erTest, method:fun signature: ()I) Accessing value from unini-
tialized register 1

That is good—the virtual machine detected our modification.

Now run the program with the -noverify (or -Xverify:none) option.

java -noverify VerifierTest

The fun method returns a seemingly random value. This is actually 2 plus the value that happened to be stored in the variable n, which never was initialized. Here is a typical printout:

1 + 2 = 15102330

To see how browsers handle verification, we wrote this program to run either as an application or an applet. Load the applet into a browser, using a file URL such as

file:///C:/CoreJavaBook/v2ch9/VerifierTest/VerifierTest.html

Then, you see an error message displayed indicating that verification has failed (see Figure 9-3).

Figure 9-3. Loading a corrupted class file raises a method verification error

graphics/09fig03.gif
 

NOTE

graphics/note.gif
 

There is a curious hole in the verifier in the Java interpreter that has been known by many people for a long time but that persists for compatibility reasons. Suppose you have two class files A.java and B.java like this:

public class A { public int field; }

public class B
{
   public static void main(String[] args)
   {
      System.out.println(new A().field);
   }
}

This program compiles and runs, of course. Now edit only the file A.java to make field private. Recompile only that file. The resulting program should fail verification since B now attempts to access a private field of A. However, up to SDK 1.4, the program will run and merrily access the private field. Only if you run the Java interpreter with the -Xverify:all option will the error be caught.

The reason is backwards compatibility with an obscure and ill-considered optimization in JDK 1.0—see http://developer.java.sun.com/developer/bugParade/bugs/4030988.html. This is not considered a security risk because only classes loaded from the local file system are exempt from verification.

Example 9-3 VerifierTest.java
 1. import java.awt.*;
 2. import java.applet.*;
 3.
 4. /**
 5.    This application demonstrates the bytecode verifier of
 6.    the virtual machine. If you use a hex editor to modify the
 7.    class file, then the virtual machine should detect the
 8.    tampering.
 9. */
10. public class VerifierTest extends Applet
11. {
12.    public static void main(String[] args)
13.    {
14.       System.out.println("1 + 2 == " + fun());
15.    }
16.
17.    /**
18.       A function that computes 1 + 2
19.       @return 3, if the code has not been corrupted
20.    */
21.    public static int fun()
22.    {
23.       int m;
24.       int n;
25.       m = 1;
26.       n = 2;
27.       // use hex editor to change to "m = 2" in class file
28.       int r = m + n;
29.       return r;
30.    }
31.
32.    public void paint(Graphics g)
33.    {
34.       g.drawString("1 + 2 == " + fun(), 20, 20);
35.    }
36. }

Security Managers and Permissions

Once a class has been loaded into the virtual machine by a class loader or by the default class loading mechanism and checked by the verifier, the third security mechanism of the Java platform springs into action: the security manager. A security manager is a class that controls whether a specific operation is permitted. Operations checked by a security manager include:

The default behavior when running Java applications is that no security manager is installed, so all these operations are permitted. The appletviewer, on the other hand, immediately installs a security manager (called AppletSecurity) that is quite restrictive.

For example, applets are not allowed to exit the virtual machine. If they try calling the exit method, then a security exception is thrown. Here is what happens in detail. The exit method of the Runtime class calls the checkExit method of the security manager. Here is the entire code of the exit method.

public void exit(int status)
{
   SecurityManager security = System.getSecurityManager();
   if (security != null)
       security.checkExit(status);
   exitInternal(status);
}

The security manager now checks if the exit request came from the browser or an individual applet. If the security manager agrees with the exit request, then the checkExit method simply returns, and normal processing continues. However, if the security manager doesn't want to grant the request, the checkExit method throws a SecurityException.

The exit method continues only if no exception occurred. It then calls the private native exitInternal method that actually terminates the virtual machine. There is no other way of terminating the virtual machine, and since the exitInternal method is private, it cannot be called from any other class. Thus, any code that attempts to exit the virtual machine must go through the exit method and thus through the checkExit security check without triggering a security exception.

Clearly, the integrity of the security policy depends on careful coding. The providers of system services in the standard library must be careful to always consult the security manager before attempting any sensitive operation.

When you run a Java application, the default is that no security manager is running. Your program can install a specific security manager by a call to the static setSecurityManager method in the System class. Once your program installs a security manager, any attempt to install a second security manager only succeeds if the first security manager agrees to be replaced. This is clearly essential; otherwise, a bad applet could install its own security manager. Thus, while it is possible to have multiple class loaders, a program in the Java programming language can be governed by only one security manager. It is up to the implementor of that security manager to decide whether to grant all classes the same access or whether to take the origins of the classes into account before deciding what to do.

The default security manager of the Java 2 platform allows both programmers and system administrators fine-grained control over individual security permissions. We describe these features in the following section. First, we give you an overview of the Java 2 platform security model. Then, we show how you can control permissions with policy files. Finally, you will see how you can define your own permission types and how you can extend the default security manager class.

Java 2 Platform Security

JDK 1.0 had a very simple security model: local classes had full permissions, and remote classes were confined to the sandbox: the applet security manager denied all access to local resources. JDK 1.1 implemented a slight modification: remote code that was signed by a trusted entity was granted the same permissions as local classes. However, both versions of the JDK provided an all-or-nothing approach. Programs either had full access or they had to play in the sandbox.

The Java 2 platform has a much more flexible mechanism. A security policy maps code sources to permission sets (see Figure 9-4).

Figure 9-4. A security policy

graphics/09fig04.gif
 

A code source has two properties: the code location (for example, a code base URL or a JAR file) and certificates. You will see later in this chapter how code can be certified by trusted parties.

A permission is any property that is checked by a security manager. SDK 1.2 implementation supports a number of permission classes, each of which encapsulates the details of a particular permission. For example, the following instance of the FilePermission class states that it is ok to read and write any file in the /tmp directory.

FilePermission p = new FilePermission("/tmp/*", "read,write");

More importantly, the default implementation of the Policy class in SDK 1.2 reads permissions from a permission file. Inside a permission file, the same read permission is expressed as

permission java.io.FilePermission "/tmp/*", "read,write";

We discuss permission files in the next section.

Figure 9-5 shows the hierarchy of permission classes in SDK 1.2.

Figure 9-5. Permission hierarchy in JDK 1.2

graphics/09fig05.gif
 

In the preceding section, you saw that the SecurityManager class has security check methods such as checkExit. These methods exist only for the convenience of the programmer and for backward compatibility. All of them call one of the two following methods:

void checkPermission(Permission p)
void checkPermission(Permission p, Object context)

The second method is used if one thread carries out a security check for another thread. The context encapsulates the call stack at the time of the check. (See Gong's book for details on how to generate and use these context objects.)

For example, here is the source code for the checkExit method.

public void checkExit()
{
   checkPermission(new RuntimePermission("exitVM"));
}

Each security manager is free to provide its own implementation of the checkPermission method. However, the JDK provides a "standard model" of how to carry out permission checks. For the remainder of this section, we describe this standard model. The standard model relies on two classes:

java.security.SecureClassLoader
java.lang.SecurityManager

These are the superclasses of the class loader and security manager that are used in all practical settings (such as applets and remote method invocation). In principle, you can install your own class loader and security manager. However, that is a complex undertaking that few programmers will want to attempt. It is much more common to extend the standard classes.

The standard model relies on a Policy object to map code sources to permissions. There can be only one Policy object in effect at any given time. The static getPolicy method of the Policy class gets the current policy.

Policy currentPolicy = Policy.getPolicy();

The principal method of the Policy class is the getPermissions method that returns the permission collection for a particular code source.

PermissionCollection permissions
   = currentPolicy.getPermissions(codeBase);

Each class has a protection domain, an object that encapsulates both the code source and the collection of permissions of the class. The getProtectionDomain method of the Class class returns that domain.

ProtectionDomain domain
   = anObject.getClass().getProtectionDomain();

The getCodeSource and getPermissions methods of the ProtectionDomain method return the code source and permission collection.

In the standard model, the permission collection is entirely dependent on the code source. The protection domain is set when the SecureClassLoader loads the class. The SecureClassLoader queries the current policy for the permissions that match the code source. It then creates a ProtectionDomain object with the given code source and permissions. Finally, it passes that object to the defineClass method. Figure 9-6 shows the relationships between these security classes.

Figure 9-6. Relationship between security classes

graphics/09fig06.gif
 

When the SecurityManager needs to check a permission, it looks at the classes of all methods currently on the call stack. It then gets the protection domains of all classes and asks each protection domain if its permission collection allows the operation that is currently being checked. If all domains agree, then the check passes. Otherwise, a SecurityException is thrown.

Why do all methods on the call stack need to allow a particular operation? Let us work through an example. Suppose the init method of an applet wants to open a file. It might call

Reader in = new FileReader(name);

The FileReader constructor calls the FileInputStream constructor, which calls the checkRead method of the security manager, which finally calls checkPermission with a FilePermission(name, "read" object. Table 9-1 shows the call stack.

Table 9-1. Call stack during permission checking
Class Method Code Source Permissions
SecurityManager SecurityManager null AllPermission
SecurityManager checkRead null AllPermission
FileInputStream constructor null AllPermission
FileReader constructor null AllPermission
applet init applet code source applet permissions
. . .      

The FileInputStream and SecurityManager classes are system classes whose CodeSource is null and whose permissions consist of an instance of the AllPermission class, which allows all operations. Clearly, their permissions alone can't determine the outcome of the check. As you can see, the checkPermission method must take into account the restricted permissions of the applet class. By checking the entire call stack, the security mechanism ensures that one class can never ask another class to carry out a sensitive operation on its behalf.

NOTE

graphics/note.gif
 

This brief discussion of permission checking shows you the basic concepts. However, there are a number of technical details that we omit here. With security, the devil lies in the details, and we encourage you to read the book by Li Gong for more information. For a more critical view of the Java platform security model, see the book Securing Java by Gary McGraw and Ed Felten [John Wiley & Sons 1999]. You can find an online version of that book at http://www.securingjava.com.

java.lang.SecurityManager

graphics/api.gif
 

java.security.Policy

graphics/api.gif
 

java.lang.Class

graphics/api.gif
 

java.lang.ClassLoader

graphics/api.gif
 

java.security.ProtectionDomain

graphics/api.gif
 

java.security.PermissionCollection

graphics/api.gif
 

java.security.CodeSource

graphics/api.gif
 

Security Policy Files

In the preceding section, you saw how the SecureClassLoader assigns permissions when loading classes, by asking a Policy object to look up the permissions for the code source of each class. In principle, you can install your own Policy class to carry out the mapping from code sources to permissions. However, in this section, you will learn about the standard policy class that the JDK 1.2 interpreter uses.

NOTE

graphics/note.gif
 

The policy class is set in the file java.security in the jre/lib subdirectory of the JDK home directory. By default, this file contains the line

policy.provider=sun.security.provider.PolicyFile

You can supply your own policy class and install it by changing this file.

The standard policy reads policy files that contain instructions for mapping code sources to permissions. You have seen these policy files in Chapter 5, where they were required to grant network access to programs that use the RMISecurityManager. Here is a typical policy file:

grant codeBase "www.horstmann.com/classes"
{
   permission java.io.FilePermission "/tmp/*", "read,write";
}

This file grants permission to read and write files in the /tmp directory to all code that was downloaded from www.horstmann.com/classes.

You can install policy files in standard locations. By default, there are two locations:

NOTE

graphics/note.gif
 

You can change the locations of these files in the java.security configuration file. The defaults are specified as

policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy

A system administrator can modify the java.security file and specify policy URLs that reside on another server and that cannot be edited by users. There can be any number of policy URLs (with consecutive numbers) in the policy file. The permissions of all files are combined.

During testing, we don't like to constantly modify these standard files. Therefore, we prefer to explicitly name the policy file that is required for each application. Simply place the permissions into a separate file, say, MyApp.policy, and start the interpreter as

java -Djava.security.policy=MyApp.policy MyApp

For applets, you use instead

appletviewer -J-Djava.security.policy=MyApplet.policy MyApplet.html

(You can use the -J option of the appletviewer to pass any command-line argument to the interpreter.)

In these examples, the MyApp.policy file is added to the other policies in effect. If you add a second equals sign, such as

java -Djava.security.policy==MyApp.policy MyApp

then your application uses only the specified policy file, and the standard policy files are ignored.

CAUTION

graphics/caution.gif
 

An easy mistake during testing is to accidentally leave a .java.policy file that grants a lot of permissions, perhaps even AllPermission, in the current directory. If you find that your application doesn't seem to pay attention to the restrictions in your policy file, check for a left-behind .java.policy file in your current directory. If you use a UNIX system, this is a particularly easy mistake to make because files whose names start with a period are not displayed by default.

As you saw previously, by default, Java applications do not install a security manager. Therefore, you won't see the effect of policy files until you install one. You can, of course, add a line

System.setSecurityManager(new SecurityManager());

into your main method. Or you can add the command-line option -Djava.security.manager when starting the interpreter.

java -Djava.security.manager
   -Djava.security.policy=MyApp.policy MyApp

In the remainder of this section, you will see in detail how to describe permissions in the policy file. We will describe the entire policy file format, except for code certificates, which we cover later in this chapter.

A policy file contains a sequence of grant entries. Each entry has the following form:

grant codesource
{
   permission_1;
   permission_2;
   . . .
}

The code source contains a code base (which can be omitted if the entry applies to code from all sources) and the names of trusted certificate signers (which can be omitted if signatures are not required for this entry).

The code base is specified as

codeBase "url"

If the URL ends in a /, then it refers to a directory. Otherwise, it is taken to be the name of a JAR file. For example

grant codeBase "www.horstmann.com/classes/" { . . . }
grant codeBase "www.horstmann.com/classes/MyApp.jar" { . . . }

The code base is an URL and should always contain forward slashes as file separators, even for file URLs in Windows. For example,

grant codeBase "file:C:/myapps/classes/"

NOTE

graphics/note.gif
 

Everyone knows that http URLs start with two slashes (http://). But there seems sufficient confusion about file URLs that the policy file reader accepts two forms of file URLs, namely, file://localFile and file:localFile. Furthermore, a slash before a Windows drive letter is optional. That is, all of the following are acceptable:

file:C:/dir/filename.ext
file:/C:/dir/filename.ext
file://C:/dir/filename.ext
file:///C:/dir/filename.ext

Actually, we tested that file:////C:/dir/filename.ext is acceptable as well, and we have no explanation for that. In UNIX/Linux, you should use the form

file:/dir/filename.ext

The permissions have the following structure:

permission className targetName, actionList;

The class name is the fully qualified class name of the permission class (such as java.io.FilePermission). The target name is a permission-specific value, for example, a file or directory name for the file permission, or a host and port for a socket permission. The action list is also permission-specific. It is a list of actions, such as read or connect, separated by commas. Some permission classes don't need target names and action lists. Table 9-2 lists the standard permissions and their actions.

As you can see from Table 9-2, most permissions simply permit a particular operation. You can think of the operation as the target with an implied action "permit". These permission classes all extend the BasicPermission class (see Figure 9-5). However, the targets for the file, socket, and property permissions are more complex, and we need to investigate them in detail.

Table 9-2. Permissions and their associated targets and actions
Permission Target Action
java.io.FilePermission file target (see text) read, write, execute, delete
java.net.SocketPermission socket target (see text) accept, connect, listen, resolve
java.util.PropertyPermission property target (see text) read, write
java.lang.RuntimePermission
createClassLoader
getClassLoader
setContextClassLoader
createSecurityManager
setSecurityManager
exitVM
setFactory
setIO
modifyThread
modifyThreadGroup
getProtectionDomain
readFileDescriptor
writeFileDescriptor
loadLibrary.libraryName
accessClassInPackage.packageName
defineClassInPackage.packageName
accessDeclaredMembers.className
queuePrintJob
stopThread
 
java.awt.AWTPermission
showWindowWithoutWarningBanner
accessClipboard
accessEventQueue
listenToAllAWTEvents
readDisplayPixels
 
java.net.NetPermission
setDefaultAuthenticator
specifyStreamHandler
requestPasswordAuthentication
 
java.lang.reflect.ReflectPermission suppressAccessChecks  
java.io.SerializablePermission
enableSubclassImplementation
enableSubstitution
java.security.SecurityPermission
getPolicy
setPolicy
getProperty.key
setProperty.key
insertProvider.providerName
removeProvider.providerName
setSystemScope
setIdentityPublicKey
setIdentityInfo
setIdentityCertificate
removeIdentityCertificate
printIdentity
clearProviderProperties.provider-
    Name
putProviderProperty.providerName
removeProviderProperty.provider-
   Name
getSignerPrivateKey
setSignerKeyPair
 
java.security.AllPermission    

File permission targets can have the following form:

file a file
directory/ a directory
directory/* all files in the directory
* all files in the current directory
directory/- all files in the directory or one of its subdirectories
- all files in the current directory or one ofits subdirectories
<<ALL FILES>> all files in the file system

For example, the following permission entry gives access to all files in the directory /myapp and any of its subdirectories.

permission java.io.FilePermission "/myapp/-",
   "read,write,delete";

You must use the \\ escape sequence to denote a backslash in a Windows file name.

permission java.io.FilePermission "c:\\myapp\\-",
   "read,write,delete";

Socket permission targets consist of a host and a port range. Host specifications have the following form:

hostname or IPaddress a single host
localhost or the empty string the local host
*.domainSuffix any host whose domain ends with the given suffix
* all hosts

Port ranges are optional and have the form:

:n a single port
:n- all ports numbered n and above
:-n all ports numbered n and below
:n1-n2 all ports in the given range

Here is an example:

permission java.net.SocketPermission
   "*.horstmann.com:8000-8999", "connect";

Finally, property permission targets can have one of two forms:

property a specific property
propertyPrefix.* all properties with the given prefix

Examples are "java.home" and "java.vm.*".

For example, the following permission entry allows a program to read all properties that start with java.vm.

permission java.util.PropertyPermission "java.vm.*", "read";

You can use system properties in policy files. The token ${property} is replaced by the property value. For example, ${user.home} is replaced by the home directory of the user. Here is a typical use of this system property in a permission entry.

permission java.io.FilePermission "${user.home}" "read,write";

To create platform-independent policy files, it is a good idea to use the file.separator property instead of explicit / or \\ separators. To make this simpler, the special notation ${/} is a shortcut for ${file.separator}. For example,

permission java.io.FilePermission "${user.home}${/}-"
   "read,write";

is a portable entry for granting permission to read and write in the user's home directory and any of its subdirectories.

The SDK comes with a rudimentary tool, called policytool, that you can use to edit policy files. When you start the tool, you can read in a policy file. The tool then displays all code sources that have permissions assigned to them (see Figure 9-7). When you click the "Edit Policy Entry" button, then all permissions for that code source are displayed (see Figure 9-8). If you select a permission and click the "Edit Permission" button, you get a dialog that lets you edit the properties of a permission entry (see Figure 9-9). As you can see, the dialog displays the valid choices for targets and actions, which can be a convenience.

Figure 9-7. The policy tool displaying code sources

graphics/09fig07.gif
 

Figure 9-8. The policy tool displaying the permissions for a code source

graphics/09fig08.gif
 

Figure 9-9. Editing a permission with the policy tool

graphics/09fig09.gif
 

Of course, this tool is not suitable for end users who would be completely mystified by most of the settings. We view it as a proof of concept for an administration tool that might be used by system administrators who don't want to worry about the exact file format of the policy files. Still, what's missing is a sensible set of categories (such as low, medium, or high security) that is meaningful to nonexperts. As a general observation, we believe that the Java 2 platform certainly contains all the pieces for a fine-grained security model, but that it could benefit from some polish in delivering these pieces to end users and system administrators.

Custom Permissions

In this section, you will see how you can supply your own permission class that users can refer to in their policy files.

To implement your permission class, you extend the Permission class and supply the following methods:

The last method is the most important. Permissions have an ordering, in which more general permissions imply more specific ones. Consider the file permission

p1 = new FilePermission("/tmp/-", "read, write");

This permission allows reading and writing of any file in the /tmp directory and any of its subdirectories.

Here are some more-specific permissions that this permission implies:

p2 = new FilePermission("/tmp/-", "read");
p3 = new FilePermission("/tmp/aFile", "read, write");
p4 = new FilePermission("/tmp/aDirectory/-", "write");

In other words, a file permission p1 implies another file permission p2 if

  1. The target file set of p1 contains the target file set of p2;

  2. The action set of p1 contains the action set of p2.

Here is an example of the use of the implies method. When the FileInputStream constructor wants to open a file for reading, it checks whether it has permission to do so. To carry out that check, a specific file permission object is passed to the the checkPermission method:

checkPermission(new FilePermission(fileName, "read"));

The security manager now asks all applicable permissions whether they imply this permission. If any one of them implies it, then the check passes.

In particular, the AllPermission implies all other permissions.

If you define your own permission classes, then you need to define a suitable notion of implication for your permission objects. Suppose, for example, that you define a TVPermission for a set-top box powered by Java technology. A permission

new TVPermission("Tommy:2-12:1900-2200", "watch,record")

might allow Tommy to watch and record television channels 2–12 between 19:00 and 22:00. You need to implement the implies method so that this permission implies a more specific one, such as

new TVPermission("Tommy:4:2000-2100", "watch")

Implementing a Permission Class

In the next sample program, we implement a new permission for monitoring the insertion of text into a text area. The program ensures that you cannot add "bad words" such as sex, drugs, and C++ into a text area. We use a custom permission class so that the list of bad words can be supplied in a policy file.

The following subclass of JTextArea asks the security manager whether it is ok to add new text.

class WordCheckTextArea extends JTextArea
{
   public void append(String text)
   {
      WordCheckPermission p
         = new WordCheckPermission(text, "insert");
      SecurityManager manager = System.getSecurityManager();
      if (manager != null) manager.checkPermission(p);
      super.append(text);
   }
}

If the security manager grants the WordCheckPermission, then the text is appended. Otherwise, the checkPermission method throws an exception.

Word check permissions have two possible actions: insert (the permission to insert a specific text) and avoid (the permission to add any text that avoids certain bad words). You should run this program with the following policy file:

grant
{
   permission WordCheckPermission "sex,drugs,C++", "avoid";
};

This policy file grants the permission to insert any text that avoids the bad words sex, drugs, and C++.

When designing the WordCheckPermission class, we must pay particular attention to the implies method. Here are the rules that control whether permission p1 implies permission p2.

  1. If p1 has action avoid and p2 has action insert, then the target of p2 must avoid all words in p1. For example, the permission

    WordCheckPermission "sex,drugs,C++", "avoid"
    

    implies the permission

    WordCheckPermission "Mary had a little lamb", "insert"
    
  2. If p1 and p2 both have action avoid, then the word set of p2 must contain all words in the word set of p1. For example, the permission

    WordCheckPermission "sex,drugs,C++", "avoid"
    

    implies the permission

    WordCheckPermission "sex,drugs", "avoid"
    
  3. If p1 and p2 both have action insert, then the text of p1 must contain the text of p2. For example, the permission

    WordCheckPermission "Mary had a little lamb", "insert"
    

    implies the permission

    WordCheckPermission "a little lamb", "insert"
    

You can find the implementation of this class in Example 9-5.

Note that you retrieve the permission target with the confusingly named getName method of the Permission class.

Since permissions are described by a pair of strings in policy files, permission classes need to be prepared to parse these strings. In particular, we use the following method to transform the comma-separated list of bad words of an avoid permission into a genuine Set.

public Set badWordSet()
{
   StringTokenizer tokenizer
       = new StringTokenizer(getName(), ",");
   Set set = new HashSet();
   while (tokenizer.hasMoreTokens())
      set.add(tokenizer.nextToken());
   return set;
}

This code allows us to use the equals and containsAll methods to compare sets. As you saw in Chapter 2, the equals method of a set class finds two sets to be equal if they contain the same elements in any order. For example, the sets resulting from "sex,drugs,C++" and "C++,drugs,sex" are equal.

CAUTION

graphics/caution.gif
 

Make sure that your permission class is a public class. The policy file loader cannot load classes with package visibility outside the boot class path, and it silently ignores any classes that it cannot find.

The program in Example 9-5 shows how the WordCheckPermission class works. Type any text into the text field and press the "Insert" button. If the security check passes, the text is appended to the text area. If not, an error message appears (see Figure 9-10).

Figure 9-10. The PermissionTest program

graphics/09fig10.gif
 

Make sure to start the program with the appropriate policy file.

java -Djava.security.policy=PermissionTest.policy
   PermissionTest

Otherwise, all attempts to insert text will fail.

CAUTION

graphics/caution.gif
 

If you carefully look at Figure 9-10, you will see that the frame window has a warning border with the misleading caption "Java Applet Window." The window caption is determined by the showWindowWithoutWarningBanner target of the java.awt.AWTPermission. If you like, you can edit the policy file to grant that permission.

Example 9-4 PermissionTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.io.*;
 4. import java.net.*;
 5. import java.security.*;
 6. import java.util.*;
 7. import javax.swing.*;
 8.
 9. /**
10.    This class demonstrates the custom WordCheckPermission.
11. */
12. public class PermissionTest
13. {
14.    public static void main(String[] args)
15.    {
16.       System.setSecurityManager(new SecurityManager());
17.       JFrame frame = new PermissionTestFrame();
18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19.       frame.show();
20.    }
21. }
22.
23. /**
24.    This frame contains a text field for inserting words into
25.    a text area that is protected from "bad words".
26. */
27. class PermissionTestFrame extends JFrame
28. {
29.    public PermissionTestFrame()
30.    {
31.       setTitle("PermissionTest");
32.       setSize(WIDTH, HEIGHT);
33.
34.       textField = new JTextField(20);
35.       JPanel panel = new JPanel();
36.       panel.add(textField);
37.       JButton openButton = new JButton("Insert");
38.       panel.add(openButton);
39.       openButton.addActionListener(new
40.          ActionListener()
41.          {
42.             public void actionPerformed(ActionEvent event)
43.             {
44.                insertWords(textField.getText());
45.             }
46.          });
47.
48.       Container contentPane = getContentPane();
49.       contentPane.add(panel, BorderLayout.NORTH);
50.
51.       textArea = new WordCheckTextArea();
52.       contentPane.add(new JScrollPane(textArea),
53.          BorderLayout.CENTER);
54.    }
55.
56.    /**
57.       Tries to insert words into the text area.
58.       Displays a dialog if the attempt fails.
59.       @param words the words to insert
60.    */
61.    public void insertWords(String words)
62.    {
63.       try
64.       {
65.          textArea.append(words + "\n");
66.       }
67.       catch (SecurityException e)
68.       {
69.          JOptionPane.showMessageDialog(this,
70.             "I am sorry, but I cannot do that.");
71.       }
72.    }
73.
74.    private JTextField textField;
75.    private WordCheckTextArea textArea;
76.    private static final int WIDTH = 400;
77.    private static final int HEIGHT = 300;
78. }
79.
80. /**
81.    A text area whose append method makes a security check
82.    to see that no bad words are added.
83. */
84. class WordCheckTextArea extends JTextArea
85. {
86.    public void append(String text)
87.    {
88.       WordCheckPermission p
89.          = new WordCheckPermission(text, "insert");
90.       SecurityManager manager = System.getSecurityManager();
91.       if (manager != null) manager.checkPermission(p);
92.       super.append(text);
93.    }
94. }
Example 9-5 WordCheckPermission.java
 1. import java.security.*;
 2. import java.util.*;
 3.
 4. /**
 5.    A permission that checks for bad words.
 6. */
 7. public class WordCheckPermission extends Permission
 8. {
 9.    /**
10.       Constructs a word check permission
11.       @param target a comma separated word list
12.       @param anAction "insert" or "avoid"
13.    */
14.    public WordCheckPermission(String target, String anAction)
15.    {
16.       super(target);
17.       action = anAction;
18.    }
19.
20.    public String getActions() { return action; }
21.
22.    public boolean equals(Object other)
23.    {
24.      if (other == null) return false;
25.      if (!getClass().equals(other.getClass())) return false;
26.      WordCheckPermission b = (WordCheckPermission)other;
27.      if (!action.equals(b.action)) return false;
28.      if (action.equals("insert"))
29.         return getName().equals(b.getName());
30.      else if (action.equals("avoid"))
31.         return badWordSet().equals(b.badWordSet());
32.      else return false;
33.    }
34.
35.    public int hashCode()
36.    {
37.       return getName().hashCode() + action.hashCode();
38.    }
39.
40.    public boolean implies(Permission other)
41.    {
42.       if (!(other instanceof WordCheckPermission)) return false;
43.       WordCheckPermission b = (WordCheckPermission)other;
44.       if (action.equals("insert"))
45.       {
46.          return b.action.equals("insert") &&
47.             getName().indexOf(b.getName()) >= 0;
48.       }
49.       else if (action.equals("avoid"))
50.       {
51.          if (b.action.equals("avoid"))
52.             return b.badWordSet().containsAll(badWordSet());
53.          else if (b.action.equals("insert"))
54.          {
55.             Iterator iter = badWordSet().iterator();
56.             while (iter.hasNext())
57.             {
58.                String badWord = (String)iter.next();
59.                if (b.getName().indexOf(badWord) >= 0)
60.                   return false;
61.             }
62.             return true;
63.          }
64.          else return false;
65.       }
66.       else return false;
67.    }
68.
69.    /**
70.       Gets the bad words that this permission rule describes.
71.       @return a set of the bad words
72.    */
73.    public Set badWordSet()
74.    {
75.       StringTokenizer tokenizer
76.          = new StringTokenizer(getName(), ",");
77.       Set set = new HashSet();
78.       while (tokenizer.hasMoreTokens())
79.          set.add(tokenizer.nextToken());
80.       return set;
81.    }
82.
83.    private String action;
84. }
java.security.Permission

graphics/api.gif
 

A Custom Security Manager

In this section, we show you how to build a simple yet complete security manager. We call it the WordCheckSecurityManager. It monitors all file access and ensures that you can't open a text file if it contains forbidden words such as sex, drugs, and C++.

We monitor file access by overriding the checkPermission method of the standard security manager class. If the permission isn't a file read permission, then we simply call super.checkPermission. To check that it is permissible to read from a file, we open the file and scan its contents. We grant access to the file only when it doesn't contain any of the forbidden words. (We only monitor files with extension .txt since we don't want to block access to system and property files.)

public class WordCheckSecurityManager extends SecurityManager
{
   public void checkPermission(Permission p)
   {
      if (p instanceof FilePermission
         && p.getActions().equals("read"))
      {
         String fileName = p.getName();
         if (containsBadWords(fileName))
            throw new SecurityException("Bad words in "
                + fileName);
      }
      else super.checkPermission(p);
   }
   . . .
}

NOTE

graphics/note.gif
 

Another way of being notified of file read requests is to override the checkRead method. The SecurityManager class implements this method to call the checkPermission method with a FilePermission object. There are close to 30 methods for other security checks that all call the checkPermission method—see the API note at the end of this section. These methods exist for historical reasons. The permission system has been introduced in the Java 2 platform. We recommend that you do not override these methods but instead carry out all permission checks in the checkPermission method.

There is just one catch in our file check scenario. Consider one possible flow of events.

But the containsBadWords method must itself read the file to check its contents, which calls the security manager again! This would result in an infinite regression unless the security manager has a way of finding out in which context it was called. The getClassContext method is the way to find out how the method was called. This method returns an array of class objects that gives all the classes whose calls are currently pending. For example, when the security manager is called for the first time, that array is

class WordCheckSecurityManager
class SecurityManager
class java.io.FileInputStream
class java.io.FileReader
class SecurityManagerFrame
. . .
class java.awt.EventDispatchThread

The class at index 0 gives the currently executing call. Unfortunately, you only get to see the classes, not the names of the pending methods. When the security manager itself attempts to open the file, it is called again and the getClassContext method returns the following array.

class WordCheckSecurityManager
class SecurityManager
class java.io.FileInputStream
class java.io.FileReader
class WordCheckSecurityManager
class WordCheckSecurityManager
class SecurityManager
class java.io.FileInputStream
class java.io.FileReader
class SecurityManagerFrame
. . .
class java.awt.EventDispatchThread

In this case, the security manager should permit the file access. How can we do this? We could test whether

getClassContext()[0] == getClassContext()[4]

but this approach is fragile. Here's an obvious case of where it can go wrong: Imagine that if the implementation changed, for example, so the FileReader constructor calls the security manager directly, then the test would be meaningless because the positions would not be the same in the array. It is far more robust to test whether any of the pending calls came from the same security manager.

Here is a method that carries out this test. Since this method is called from checkPermission, there are at least two copies of the security manager class on the call stack. We skip these first and then look for another instance of the same security manager.

boolean inSameManager()
{
   Class[] cc = getClassContext();

   // skip past current set of calls to this manager
   int i = 0;
   while (i < cc.length && cc[0] == cc[i])
      i++;

   // check if there is another call to this manager
   while (i < cc.length)
   {
      if (cc[0] == cc[i]) return true;
      i++;
   }
   return false;
}

We call this method in the checkPermission method. If we find that the security manager is invoked recursively, then we do not call the containsBadWords method again.

if (p instanceof FilePermission
   && p.getActions().equals("read"))
{
   if (inSameManager())
      return;
   String fileName = p.getName();
   if (containsBadWords(fileName))
      throw new SecurityException("Bad words in "
         + fileName);
}

Example 9-6 shows a program that puts this security manager to work. The security manager is installed in the main method. When running the program, you can specify a file. The program will load its contents into the text area. However, if the file fails the security check, the program catches the security exception and displays a message instead (see Figure 9-11). For example, you can display "Alice in Wonderland," but the program refuses to load "The Count of Monte Cristo."

Figure 9-11. The SecurityManagerTest program

graphics/09fig11.gif
 

NOTE

graphics/note.gif
 

You may wonder why we don't use a JFileChooser to select a file name. The JFileChooser class tries to read the files that it displays, probably to find out which of them are files and which are directories.

You need to be careful how you invoke this program. The WordCheckSecurityManager class itself needs to be given AllPermission. The reason for this is subtle. The WordCheckSecurityManager class calls the SecurityManager superclass for all permissions other than file read permissions. When the SecurityManager class evaluates a permission, it looks whether all methods on the call stack should be granted that particular permission. The WordCheckSecurityManager is one of those classes. But it is not a system class, so you must explicitly grant it all permissions without also granting all permissions to the other classes of the program.

To separate the WordCheckSecurityManager class files from the other class files, make a JAR file containing just that class file.

jar cvf WordCheck.jar WordCheckSecurityManager.class

Then delete the WordCheckSecurityManager.class file.

Next, create a policy file, WordCheck.policy, with the following contents:

grant codeBase "file:WordCheck.jar"
{
   permission java.security.AllPermission;
};

This policy grants all permissions to the classes in the WordCheck.jar file. Finally, start the application as follows:

java -Djava.security.policy=WordCheck.policy
   -classpath WordCheck.jar:. SecurityManagerTest

TIP

graphics/tip.gif
 

If you are thinking of changing the security manager in your own programs, you should first investigate whether you can instead use the standard security manager and a custom permission, as described in the preceding section. Writing a security manager is error prone and can cause subtle security flaws. It is much better to use the standard security manager and augment the permission system instead.

Example 9-6 SecurityManagerTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.io.*;
 4. import java.net.*;
 5. import java.util.*;
 6. import javax.swing.*;
 7.
 8. /**
 9.    This class demonstrates the use of a custom security manager
10.    that prohibits the reading of text files containing bad words.
11. */
12. public class SecurityManagerTest
13. {
14.    public static void main(String[] args)
15.    {
16.       System.setSecurityManager(new WordCheckSecurityManager());
17.       JFrame frame = new SecurityManagerFrame();
18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19.       frame.show();
20.    }
21. }
22.
23. /**
24.    This frame contains a text field to enter a file name and
25.    a text area to show the contents of the loaded file.
26. */
27. class SecurityManagerFrame extends JFrame
28. {
29.    public SecurityManagerFrame()
30.    {
31.       setTitle("SecurityManagerTest");
32.       setSize(WIDTH, HEIGHT);
33.
34.       fileNameField = new JTextField(20);
35.       JPanel panel = new JPanel();
36.       panel.add(new JLabel("Text file:"));
37.       panel.add(fileNameField);
38.       JButton openButton = new JButton("Open");
39.       panel.add(openButton);
40.       openButton.addActionListener(new
41.          ActionListener()
42.          {
43.             public void actionPerformed(ActionEvent event)
44.             {
45.                loadFile(fileNameField.getText());
46.             }
47.          });
48.
49.       Container contentPane = getContentPane();
50.       contentPane.add(panel, "North");
51.
52.       fileText = new JTextArea();
53.       contentPane.add(new JScrollPane(fileText), "Center");
54.    }
55.
56.    /**
57.       Attempt to load a file into the text area. If a security
58.       exception is caught, a message is inserted into the text
59.       area instead.
60.       @param filename the file name
61.    */
62.    public void loadFile(String filename)
63.    {
64.       try
65.       {
66.          fileText.setText("");
67.          BufferedReader in
68.             = new BufferedReader(new FileReader(filename));
69.          String s;
70.          while ((s = in.readLine()) != null)
71.          fileText.append(s + "\n");
72.          in.close();
73.       }
74.       catch (IOException e)
75.       {
76.          fileText.append(e + "\n");
77.       }
78.       catch (SecurityException e)
79.       {
80.          fileText.append("I am sorry, but I cannot do that.");
81.       }
82.    }
83.
84.    private JTextField fileNameField;
85.    private JTextArea fileText;
86.    private static final int WIDTH = 400;
87.    private static final int HEIGHT = 300;
88. }
Example 9-7 WordCheckSecurityManager.java
 1. import java.io.*;
 2. import java.security.*;
 3.
 4. /**
 5.    This security manager checks whether bad words are
 6.    encountered when reading a file.
 7. */
 8. public class WordCheckSecurityManager extends SecurityManager
 9. {
10.    public void checkPermission(Permission p)
11.    {
12.       if (p instanceof FilePermission
13.          && p.getActions().equals("read"))
14.       {
15.          if (inSameManager())
16.             return;
17.          String fileName = p.getName();
18.          if (containsBadWords(fileName))
19.             throw new SecurityException("Bad words in "
20.                + fileName);
21.       }
22.       else super.checkPermission(p);
23.    }
24.
25.    /**
26.       Returns true if this manager is called while there
27.       is another call to itself pending.
28.       @return true if there are multiple calls to this manager
29.    */
30.    public boolean inSameManager()
31.    {
32.       Class[] cc = getClassContext();
33.
34.       // skip past current set of calls to this manager
35.       int i = 0;
36.       while (i < cc.length && cc[0] == cc[i])
37.          i++;
38.
39.       // check if there is another call to this manager
40.       while (i < cc.length)
41.       {
42.          if (cc[0] == cc[i]) return true;
43.          i++;
44.       }
45.       return false;
46.    }
47.
48.    /**
49.       Checks if a file contains bad words.
50.       @param fileName the name of the file
51.       @return true if the file name ends with .txt and it
52.       contains at least one bad word.
53.    */
54.    boolean containsBadWords(String fileName)
55.    {
56.       if (!fileName.toLowerCase().endsWith(".txt")) return false;
57.          // only check text files
58.       BufferedReader in = null;
59.       try
60.       {
61.          in = new BufferedReader(new FileReader(fileName));
62.          String s;
63.          while ((s = in.readLine()) != null)
64.          {
65.             for (int i = 0; i < badWords.length; i++)
66.             if (s.toLowerCase().indexOf(badWords[i]) != -1)
67.                return true;
68.          }
69.          in.close();
70.          return false;
71.       }
72.       catch(IOException e)
73.       {
74.          return true;
75.       }
76.       finally
77.       {
78.          if (in != null)
79.             try { in.close(); } catch (IOException e) {}
80.       }
81.    }
82.
83.    private String[] badWords = { "sex", "drugs", "c++" };
84. }
java.lang.System

graphics/api.gif
 

java.lang.SecurityManager

graphics/api.gif
 

User Authentication

Starting with SDK 1.4, it is possible to attach permissions to users, so that you can specify, for example, that Harry has a particular FilePermission but other users do not. The syntax is like this:

grant principal com.sun.security.auth.UnixPrincipal "harry"
{
   permission java.io.FilePermission "<<ALL FILES>>";
};

Here, com.sun.security.auth.UnixPrincipal is a class whose getName method returns the UNIX login name.

The Java Authentication and Authorization Service (JAAS) also supports NT logins, Kerberos authentication, and certificate-based authentication.

You must program a user login to allow the security manager to check such a grant statement. Here is the basic outline of the login code:

try
{
   System.setSecurityManager(new SecurityManager());
   LoginContext context = new LoginContext("Login1");
   context.login();
   System.out.println("Authentication successful.");
   // get the authenticated Subject
   Subject subject = context.getSubject();
   . . .
   context.logout();
}
catch (LoginException exception)
{
   exception.printStackTrace();
}

Now the subject denotes the individual who has been authenticated.

The string parameter "Login1" in the LoginContext constructor refers to an entry with the same name in the JAAS configuration file. Here is a sample configuration file:

Login1
{
   com.sun.security.auth.module.UnixLoginModule required;
};

Login2
{
   com.whizzbang.auth.module.SmartCardModule sufficient;
   com.whizzbang.auth.module.RetinaScanModule sufficient;
}

This configuration file requires that the user have a UNIX login for the first login policy. It is also possible to list other authentication modules, and label them sufficient, requisite, or optional. The authentication modules are executed in turn, until a sufficient module succeeds, a requisite module fails, or the end of the module list is reached.

Of course, there are no biometric login modules contained in the SDK. The SDK contains the following modules in the com.sun.security.auth.module package:

UnixLoginModule
NTLoginModule
Krb5LoginModule
JndiLoginModule
KeyStoreLoginModule

A login authenticates a subject, which can have multiple principals. As you have seen in the grant statement, principals govern permissions. Some permissions may be tied to a user name, but more likely, permissions are tied to group membership. The UnixNumericGroupPrincipal class can be used to test for membership in a UNIX group.

When a user has logged in, then you need to run the code that requires checking of principals in a separate access control context. Use the static doAs method to start a new PrivilegedAction whose run method executes the code:

Subject.doAs(subject, new
   PrivilegedAction()
   {
      public Object run()
      {
        // actions here are checked against subject principals
         . . .
         return null;
      }
   });

If the actions can throw checked exceptions, then you need to implement the PrivilegedExceptionAction interface instead.

The program in Example 9-8 demonstrates how to restrict permissions to certain users. The AuthTest program runs another Java program after performing a login. The name of the other program and its command line arguments are given on the command line, such as

java options AuthTest LineCount ../../gutenberg/alice30.txt

Here, LineCount is another program that simply counts the lines of all files specified on the command line (see Example 9-9).

To make this example work, you need to package the code for the login classes and the program classes into two separate JAR files:

javac AuthTest.java
jar cvf login.jar AuthTest*.class
javac LineCount.java
jar cvf prog.jar LineCount.class

If you look at the policy file in Example 9-10, you will see that the UNIX user with the name harry has the permission to read all files. Change harry to your login name. (If you run this test on Windows NT, change UNIX to NT in both AuthTest.policy and jaas.config—see Example 9-11). Then run the command

java -classpath "login.jar:prog.jar"
   -Djava.security.policy=AuthTest.policy
   -Djava.security.auth.login.config=jaas.config
   AuthTest LineCount ../../gutenberg/alice30.txt

On Windows, use

java -classpath "login.jar;prog.jar"
   -Djava.security.policy=AuthTest.policy
   -Djava.security.auth.login.config=jaas.config
   AuthTest LineCount ..\..\gutenberg\alice30.txt

The LineCount program should now display a line count. However, if you change the login name in the AuthTest.policy file, then a security exception should be thrown because you no longer have the required permission.

CAUTION

graphics/caution.gif
 

Be careful to follow these instructions exactly. It is very easy to get the setup wrong by making seemingly innocuous changes. In particular, note that the permissions must be added both to the grant clause of the login.jar file and the grant clause of the principal. (Only the intersection of the rights is granted when the doAs method executes.) Also, you must add the program files to a JAR file. If you use the class path "login.jar:.", then the permissions are not applied to the classes loaded from the file system. That may well be a bug.

In this section, we have only scratched the surface of the JAAS capabilities. For more information, read the JAAS Reference Guide that is a part of the SDK documentation.

Example 9-8 AuthTest.java
 1. import java.lang.reflect.*;
 2. import java.security.*;
 3. import javax.security.auth.*;
 4. import javax.security.auth.login.*;
 5.
 6. /**
 7.    This program authenticates a user via the Unix login
 8.    and then executes the program specified by the command line
 9.    with the user's principals.
10. */
11. public class AuthTest
12. {
13.    public static void main(final String[] args)
14.    {
15.        try
16.        {
17.           System.setSecurityManager(new SecurityManager());
18.
19.           LoginContext context = new LoginContext("Login1");
20.           context.login();
21.           System.out.println("Authentication successful.");
22.           Subject subject = context.getSubject();
23.           Subject.doAs(subject, new
24.              PrivilegedExceptionAction()
25.              {
26.                 public Object run() throws Exception
27.                 {
28.                    // invoke the main method of the class
29.                    // specified in args[0], with command line
30.                    // arguments args[1] args[2] . . .
31.                    Class cl = Class.forName(args[0]);
32.                    Method mainMethod = cl.getMethod("main",
33.                       new Class[] { String[].class });
34.                    String[] args1 = new String[args.length - 1];
35.                    System.arraycopy(args, 1,
36.                       args1, 0, args1.length);
37.                    mainMethod.invoke(null,
38.                       new Object[] { args1 });
39.                    return null;
40.                 }
41.              });
42.
43.           context.logout();
44.        }
45.        catch (LoginException exception)
46.        {
47.           exception.printStackTrace();
48.        }
49.        catch (PrivilegedActionException exception)
50.        {
51.           exception.printStackTrace();
52.        }
53.    }
54. }
Example 9-9 LineCount.java
 1. import java.io.*;
 2.
 3. /**
 4.    This is a demonstration program that can be launched from
 5.    the AuthTest program. It simply counts the lines in all
 6.    files whose names are specified as command-line arguments.
 7. */
 8. public class LineCount
 9. {
10.    public static void main(String[] args) throws Exception
11.    {
12.       for (int i = 0; i < args.length; i++)
13.       {
14.          int count = 0;
15.          String line;
16.          BufferedReader reader
17.             = new BufferedReader(new FileReader(args[i]));
18.          while ((line = reader.readLine()) != null) count++;
19.          System.out.println(args[i] + ": " + count);
20.       }
21.    }
22. }
Example 9-10 AuthTest.policy
 1. grant codebase "file:login.jar"
 2. {
 3.    permission javax.security.auth.AuthPermission
 4.       "createLoginContext.Login1";
 5.    permission javax.security.auth.AuthPermission "doAs";
 6.    permission java.io.FilePermission "<<ALL FILES>>", "read";
 7. };
 8.
 9. grant principal com.sun.security.auth.UnixPrincipal "harry"
10. {
11.    permission java.io.FilePermission "<<ALL FILES>>", "read";
12. };
Example 9-11 jaas.config
 1. Login1
 2. {
 3.    com.sun.security.auth.module.UnixLoginModule required;
 4. };
javax.security.auth.login.LoginContext

graphics/api.gif
 

javax.security.auth.Subject

graphics/api.gif
 

java.security.PrivilegedAction

graphics/api.gif
 

java.security.PrivilegedExceptionAction

graphics/api.gif
 

java.security.Principal

graphics/api.gif
 

Digital Signatures

As we said earlier, applets were what started the craze over the Java platform. In practice, people discovered that although they could write animated applets like the famous "nervous text" applet, applets could not do a whole lot of useful stuff in the JDK 1.0 security model. For example, because applets under JDK 1.0 were so closely supervised, they couldn't do much good on a corporate intranet, even though relatively little risk attaches to executing an applet from your company's secure intranet. It quickly became clear to Sun that for applets to become truly useful, it was important for users to be able to assign different levels of security, depending on where the applet originated. If an applet comes from a trusted supplier and it has not been tampered with, the user of that applet can then decide whether to give the applet more privileges.

This added control is now possible because of the applet-signing mechanism in Java 1.1. To give more trust to an applet, we need to know two things:

  1. Where did the applet come from?

  2. Was the code corrupted in transit?

In the past 50 years, mathematicians and computer scientists have developed sophisticated algorithms for ensuring the integrity of data and for electronic signatures. The java.security package contains implementations of many of these algorithms. Fortunately, you don't need to understand the underlying mathematics to use the algorithms in the java.security package. In the next sections, you will see how message digests can detect changes in data files and how digital signatures can prove the identity of the signer.

Message Digests

A message digest is a digital fingerprint of a block of data. For example, the so called SHA1 (secure hash algorithm #1) condenses any data block, no matter how long, into a sequence of 160 bits (20 bytes). As with real fingerprints, one hopes that no two messages have the same SHA1 fingerprint. Of course, that cannot be true—there are only 2160 SHA1 fingerprints, so there must be some messages with the same fingerprint. But 2160 is so large that the probability of duplication occurring is negligible. How negligible? According to James Walsh in True Odds: How Risks Affect Your Everyday Life [Merritt Publishing 1996], the chance that you will die from being struck by lightning is about one in 30,000. Now, think of 9 other people, for example, your 9 least favorite managers or professors. The chance that you and all of them will die from lightning strikes is higher than that of a forged message having the same SHA1 fingerprint as the original. (Of course, more than 10 people, none of whom you are likely to know, will die from lightning. But we are talking about the far slimmer chance that your particular choice of people will be wiped out.)

A message digest has two essential properties.

  1. If one bit or several bits of the data are changed, then the message digest also changes.

  2. A forger who is in possession of a given message cannot construct a fake message that has the same message digest as the original.

The second property is again a matter of probabilities, of course. Consider the following message by the billionaire father:

"Upon my death, my property shall be divided equally among my children; however, my son George shall receive nothing."

That message has an SHA1 fingerprint of

2D 8B 35 F3 BF 49 CD B1 94 04 E0 66 21 2B 5E 57 70 49 E1 7E

The distrustful father has deposited the message with one attorney and the fingerprint with another. Now, suppose George can bribe the lawyer holding the message. He wants to change the message so that Bill gets nothing. Of course, that changes the fingerprint to a completely different bit pattern:

2A 33 0B 4B B3 FE CC 1C 9D 5C 01 A7 09 51 0B 49 AC 8F 98 92

Can George find some other wording that matches the fingerprint? If he had been the proud owner of a billion computers from the time the Earth was formed, each computing a million messages a second, he would not yet have found a message he could substitute.

A number of algorithms have been designed to compute these message digests. The two best-known are SHA1, the secure hash algorithm developed by the National Institute of Standards and Technology, and MD5, an algorithm invented by Ronald Rivest of MIT. Both algorithms scramble the bits of a message in ingenious ways. For details about these algorithms, see, for example, Cryptography and Network Security by William Stallings [Prentice Hall 1998]. Note that recently, subtle regularities have been discovered in MD5, and some cryptographers recommend avoiding it and using SHA1 for that reason. (Both algorithms are easy to compute.)

The Java programming language implements both SHA1 and MD5. The MessageDigest class is a factory for creating objects that encapsulate the fingerprinting algorithms. It has a static method, called getInstance, that returns an object of a class that extends the MessageDigest class. This means the MessageDigest class serves double duty:

For example, here is how you obtain an object that can compute SHA fingerprints.

MessageDigest alg = MessageDigest.getInstance("SHA-1");

(To get an object that can compute MD5, use the string "MD5" as the argument to getInstance.)

After you have obtained a MessageDigest object, you feed it all the bytes in the message by repeatedly calling the update method. For example, the following code passes all bytes in a file to the alg object created above to do the fingerprinting:

FileInputStream in = new FileInputStream(f);
int ch;

while ((ch = in.read()) != -1)
   alg.update((byte)ch);

Alternatively, if you have the bytes in an array, you can update the entire array at once:

byte[] bytes = . . .;
alg.update(bytes);

When you are done, call the digest method. This method pads the input—as required by the fingerprinting algorithm—does the computation, and returns the digest as an array of bytes.

byte[] hash = alg.digest();

The program in Example 9-12 computes a message digest, using either SHA or MD5. You can load the data to be digested from a file, or you can type a message in the text area. Figure 9-12 shows the application.

Figure 9-12. Computing a message digest

graphics/09fig12.gif
 

Example 9-12 MessageDigestTest.java
  1. import java.io.*;
  2. import java.security.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program computes the message digest of a file
  9.    or the contents of a text area.
 10. */
 11. public class MessageDigestTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new MessageDigestFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19. }
 20.
 21. /**
 22.    This frame contains a menu for computing the message
 23.    digest of a file or text area, radio buttons to toggle between
 24.    SHA-1 and MD5, a text area, and a text field to show the
 25.    message digest.
 26. */
 27. class MessageDigestFrame extends JFrame
 28. {
 29.    public MessageDigestFrame()
 30.    {
 31.       setTitle("MessageDigestTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       JPanel panel = new JPanel();
 35.       ButtonGroup group = new ButtonGroup();
 36.       addRadioButton(panel, "SHA-1", group);
 37.       addRadioButton(panel, "MD5", group);
 38.
 39.       Container contentPane = getContentPane();
 40.
 41.       contentPane.add(panel, BorderLayout.NORTH);
 42.       contentPane.add(new JScrollPane(message),
 43.          BorderLayout.CENTER);
 44.       contentPane.add(digest, BorderLayout.SOUTH);
 45.       digest.setFont(new Font("Monospaced", Font.PLAIN, 12));
 46.
 47.       setAlgorithm("SHA-1");
 48.
 49.       JMenuBar menuBar = new JMenuBar();
 50.       JMenu menu = new JMenu("File");
 51.       JMenuItem fileDigestItem = new JMenuItem("File digest");
 52.       fileDigestItem.addActionListener(new
 53.          ActionListener()
 54.          {
 55.             public void actionPerformed(ActionEvent event)
 56.             {
 57.                loadFile();
 58.             }
 59.          });
 60.       menu.add(fileDigestItem);
 61.       JMenuItem textDigestItem
 62.          = new JMenuItem("Text area digest");
 63.       textDigestItem.addActionListener(new
 64.          ActionListener()
 65.          {
 66.             public void actionPerformed(ActionEvent event)
 67.             {
 68.                String m = message.getText();
 69.                computeDigest(m.getBytes());
 70.             }
 71.          });
 72.       menu.add(textDigestItem);
 73.       menuBar.add(menu);
 74.       setJMenuBar(menuBar);
 75.    }
 76.
 77.    /**
 78.       Adds a radio button to select an algorithm.
 79.       @param c the container into which to place the button
 80.       @param name the algorithm name
 81.       @param g the button group
 82.    */
 83.    public void addRadioButton(Container c, final String name,
 84.       ButtonGroup g)
 85.    {
 86.       ActionListener listener = new
 87.          ActionListener()
 88.          {  public void actionPerformed(ActionEvent event)
 89.             {
 90.                setAlgorithm(name);
 91.             }
 92.          };
 93.       JRadioButton b
 94.          = new JRadioButton(name, g.getButtonCount() == 0);
 95.       c.add(b);
 96.       g.add(b);
 97.       b.addActionListener(listener);
 98.    }
 99.
100.    /**
101.       Sets the algorithm used for computing the digest.
102.       @param alg the algorithm name
103.    */
104.    public void setAlgorithm(String alg)
105.    {
106.       try
107.       {
108.          currentAlgorithm = MessageDigest.getInstance(alg);
109.          digest.setText("");
110.       }
111.       catch(NoSuchAlgorithmException e)
112.       {
113.          digest.setText("" + e);
114.       }
115.    }
116.
117.    /**
118.       Loads a file and computes its message digest.
119.    */
120.    public void loadFile()
121.    {
122.       JFileChooser chooser = new JFileChooser();
123.       chooser.setCurrentDirectory(new File("."));
124.
125.       int r = chooser.showOpenDialog(this);
126.       if (r == JFileChooser.APPROVE_OPTION)
127.       {
128.          String name
129.             = chooser.getSelectedFile().getAbsolutePath();
130.          computeDigest(loadBytes(name));
131.       }
132.    }
133.
134.    /**
135.       Loads the bytes in a file.
136.       @param name the file name
137.       @return an array with the bytes in the file
138.    */
139.    public byte[] loadBytes(String name)
140.    {
141.       FileInputStream in = null;
142.
143.       try
144.       {  in = new FileInputStream(name);
145.          ByteArrayOutputStream buffer
146.             = new ByteArrayOutputStream();
147.          int ch;
148.          while ((ch = in.read()) != -1)
149.             buffer.write(ch);
150.          return buffer.toByteArray();
151.       }
152.       catch (IOException e)
153.       {
154.          if (in != null)
155.          {
156.             try { in.close(); } catch (IOException e2) {}
157.          }
158.          return null;
159.       }
160.    }
161.
162.    /**
163.       Computes the message digest of an array of bytes
164.       and displays it in the text field.
165.       @param b the bytes for which the message digest should
166.       be computed.
167.    */
168.    public void computeDigest(byte[] b)
169.    {
170.       currentAlgorithm.reset();
171.       currentAlgorithm.update(b);
172.       byte[] hash = currentAlgorithm.digest();
173.       String d = "";
174.       for (int i = 0; i < hash.length; i++)
175.       {
176.          int v = hash[i] & 0xFF;
177.          if (v < 16) d += "0";
178.          d += Integer.toString(v, 16).toUpperCase() + " ";
179.       }
180.       digest.setText(d);
181.    }
182.
183.    private JTextArea message = new JTextArea();
184.    private JTextField digest = new JTextField();
185.    private MessageDigest currentAlgorithm;
186.    private static final int WIDTH = 400;
187.    private static final int HEIGHT = 300;
188. }
java.security.MessageDigest

graphics/api.gif
 

Message Signing

In the last section, you saw how to compute a message digest, a fingerprint for the original message. If the message is altered, then the fingerprint of the altered message will not match the fingerprint of the original. If the message and its fingerprint are delivered separately, then the recipient can check whether the message has been tampered with. However, if both the message and the fingerprint were intercepted, it is an easy matter to modify the message and then recompute the fingerprint. After all, the message digest algorithms are publicly known, and they don't require any secret keys. In that case, the recipient of the forged message and the recomputed fingerprint would never know that the message has been altered. In this section, you will see how digital signatures can authenticate a message. When a message is authenticated, you know

To understand how digital signatures work, we need to explain a few concepts from the field called public key cryptography. Public key cryptography is based on the notion of a public key and private key. The idea is that you tell everyone in the world your public key. However, only you hold the private key, and it is important that you safeguard it and don't release it to anyone else. The keys are matched by mathematical relationships, but it is believed to be practically impossible to compute one from the other. That is, even though everyone knows your public key, they can't compute your private key in your lifetime, no matter how many computing resources they have available.

It may seem difficult to believe that nobody can compute the private key from the public keys, but nobody has ever found an algorithm to do this for the encryption algorithms that are in common use today. If the keys are sufficiently long, brute force—simply trying all possible keys—would require more computers than can be built from all the atoms in the solar system, crunching away for thousands of years. Of course, it is possible that someone could come up with algorithms for computing keys that are much more clever than brute force. For example, the RSA algorithm (the encryption algorithm invented by Rivest, Shamir, and Adleman) depends on the difficulty of factoring large numbers. For the last 20 years, many of the best mathematicians have tried to come up with good factoring algorithms, but so far with no success. For that reason, most cryptographers believe that keys with a "modulus" of 2,000 bits or more are currently completely safe from any attack.

There are two kinds of public/private key pairs: for encryption and for authentication. If anyone sends you a message that was encrypted with your public encryption key, then you can decrypt it with your private decryption key, but nobody else can. Conversely, if you sign a message with your private authentication key, then anyone else can verify the signature by checking with your public key. The verification passes only for messages that you signed, and it fails if anyone else used his key to sign the message. (Kahn remarks in the new edition of his book The Codebreakers that this was the first new idea in cryptography in hundreds of years.)

Many cryptographic algorithms, such as RSA and DSA (the Digital Signature Algorithm), use this idea. The exact structure of the keys and what it means for them to match depend on the algorithm. For example, here is a matching pair of public and private DSA keys.

Public key:

p: fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae16
17ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee7375
92e17

q: 962eddcc369cba8ebb260ee6b6a126d9346e38c5

g: 678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d1427
1b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be79
4ca4

y: c0b6e67b4ac098eb1a32c5f8c4c1f0e7e6fb9d832532e27d0bdab9ca2d2a
8123ce5a8018b8161a760480fadd040b927281ddb22cb9bc4df596d7de4d1b97
7d50

Private key:

p: fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae16
17ae01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee73759
2e17

q: 962eddcc369cba8ebb260ee6b6a126d9346e38c5

g: 678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d1427
1b9e35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be79
4ca4

x: 146c09f881656cc6c51f27ea6c3a91b85ed1d70a

There is a mathematical relationship between these keys, but the exact nature of the relationship is not interesting for practical programming. (If you are interested, you can look it up in Cryptography & Network Security or The Handbook of Cryptography mentioned earlier.)

The obvious question is how to generate the pair of keys. Usually, this is done by feeding the result of some random process in to a deterministic procedure that returns the key pair to you. Luckily, how to get a random key pair for public key cryptography is not a question anyone but cryptographers and mathematicians need to worry about.

Here is how it works in practice. Suppose Alice wants to send Bob a message, and Bob wants to know this message came from Alice and not an impostor. Alice writes the message and then signs the message digest with her private key. Bob gets a copy of her public key. Bob then applies the public key to verify the signature. If the verification passes, then Bob can be assured of two facts:

  1. The original message has not been altered

  2. The message was signed by Alice, the holder of the private key that matches the public key that Bob used for verification

See Figure 9-13.

Figure 9-13. Public key signature exchange using DSA

graphics/09fig13.gif
 

You can see why security for private keys is all-important. If someone steals Alice's private key or if a government can require her to turn it over, then she is in trouble. The thief or a government agent can impersonate her by sending messages, money transfer instructions, and so on, that others will believe to have come from Alice.

The Java security package comes with DSA. If you want to use RSA, you'll need to buy the classes from RSA (www.rsa.com). Let us put the DSA algorithm to work. Actually, there are three algorithms:

  1. To generate a key pair;

  2. To sign a message;

  3. To verify a signature.

Of course, you generate a key pair only once and then use it for signing and verifying many messages. To generate a new random key pair, make sure you use truly random numbers. For example, the regular random number generator in the Random class, seeded by the current date and time, is not random enough. (The jargon says the basic random number generator in java.util is not "cryptographically secure.") For example, supposing the computer clock is accurate to 1/10 of a second; then, there are at most 864,000 seeds per day. If an attacker knows the day a key was issued (as can often be deduced from the expiration date), then it is an easy matter to generate all possible seeds for that day.

The SecureRandom class generates random numbers that are far more secure than those produced by the Random class. You still need to provide a seed to start the number sequence at a random spot. The best method for doing this is to obtain random input from a hardware device such as a white-noise generator. Another reasonable source for random input is to ask the user to type away aimlessly on the keyboard. But each keystroke should contribute only one or two bits to the random seed. Once you gather such random bits in an array of bytes, you pass it to the setSeed method.

SecureRandom secrand = new SecureRandom();
byte[] b = new byte[20];
// fill with truly random bits
secrand.setSeed(b);

If you don't seed the random number generator, then it will compute its own 20-byte seed by launching threads, putting them to sleep, and measuring the exact time when they are awakened.

NOTE

graphics/note.gif
 

This is an innovative algorithm that, at this point, is not known to be safe. And, in the past, algorithms that relied on timing other components of the computer, such as hard disk access time, were later shown not to be completely random.

Once you seed the generator, you can then draw random bytes with the nextBytes method.

byte[] randomBytes = new byte[64];
secrand.nextBytes(randomBytes);

Actually, to compute a new DSA key, you don't compute the random numbers yourself. You just pass the random number generator object to the DSA key generation algorithm.

To make a new key pair, you need a KeyPairGenerator object. Just as with the MessageDigest class of the preceding section, the KeyPairGenerator class is both a factory class and the superclass for actual key pair generation algorithms. To get a DSA key pair generator, you call the getInstance method with the string "DSA".

KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");

The returned object is actually an object of the class sun.security.provider.DSAKeyPairGenerator, which is a subclass of KeyPairGenerator.

To generate keys, you must initialize the key generation algorithm object with the key strength and a secure random number generator. Note that the key strength is not the length of the generated keys but the size of one of the building blocks of the key. In the case of DSA, it is the number of bits in the modulus, one of the mathematical quantities that makes up the public and private keys. Suppose you want to generate a key with a modulus of 512 bits:

SecureRandom secrand = new SecureRandom();
secrand.setSeed(...);
keygen.initialize(512, secrand);

Now you are ready to generate key pairs.

KeyPair keys = keygen.generateKeyPair();
KeyPair morekeys = keygen.generateKeyPair();

Each key pair has a public and a private key.

PublicKey pubkey = keys.getPublic();
PrivateKey privkey = keys.getPrivate();

To sign a message, you need a signature algorithm object. You use the Signature factory class:

Signature signalg = Signature.getInstance("DSA");

Signature algorithm objects can be used both to sign and to verify a message. To prepare the object for message signing, use the initSign method and pass the private key to the signature algorithm.

signalg.initSign(privkey);

Now, you use the update method to add bytes to the algorithm objects, in the same way as with the message digest algorithm.

while ((ch = in.read()) != -1)
   signalg.update((byte)ch);

Finally, you can compute the signature with the sign method. The signature is returned as an array of bytes.

byte[] signature = signalg.sign();

The recipient of the message must obtain a DSA signature algorithm object and prepare it for signature verification by calling the initVerify method with the public key as parameter.

Signature verifyalg = Signature.getInstance("DSA");
verifyalg.initVerify(pubkey);

Then, the message must be sent to the algorithm object.

while ((ch = in.read()) != -1)
   verifyalg.update((byte)ch);

Finally, you can verify the signature.

boolean check = verifyalg.verify(signature);

If the verify method returns true, then the signature was a valid signature of the message that was signed with the matching private key. That is, both the sender and the contents of the message have been authenticated.

Example 9-13 demonstrates the key generation, signing, and verification processes.

Example 9-13 SignatureTest.java
 1. import java.security.*;
 2.
 3. /**
 4.    This program demonstrates how to sign a message with a
 5.    private DSA key and verify it with the matching public key.
 6. */
 7. public class SignatureTest
 8. {
 9.    public static void main(String[] args)
10.    {
11.       try
12.       {
13.          KeyPairGenerator keygen
14.             = KeyPairGenerator.getInstance("DSA");
15.          SecureRandom secrand = new SecureRandom();
16.          keygen.initialize(512, secrand);
17.
18.          KeyPair keys1 = keygen.generateKeyPair();
19.          PublicKey pubkey1 = keys1.getPublic();
20.          PrivateKey privkey1 = keys1.getPrivate();
21.
22.          KeyPair keys2 = keygen.generateKeyPair();
23.          PublicKey pubkey2 = keys2.getPublic();
24.          PrivateKey privkey2 = keys2.getPrivate();
25.
26.          Signature signalg = Signature.getInstance("DSA");
27.          signalg.initSign(privkey1);
28.          String message
29.             = "Pay authors a bonus of $20,000.";
30.          signalg.update(message.getBytes());
31.          byte[] signature = signalg.sign();
32.
33.          Signature verifyalg = Signature.getInstance("DSA");
34.          verifyalg.initVerify(pubkey1);
35.          verifyalg.update(message.getBytes());
36.          if (!verifyalg.verify(signature))
37.             System.out.print("not ");
38.          System.out.println("signed with private key 1");
39.
40.          verifyalg.initVerify(pubkey2);
41.          verifyalg.update(message.getBytes());
42.          if (!verifyalg.verify(signature))
43.             System.out.print("not ");
44.          System.out.println("signed with private key 2");
45.       }
46.       catch(Exception e)
47.       {
48.          e.printStackTrace();
49.       }
50.    }
51. }
java.security.KeyPairGenerator

graphics/api.gif
 

java.security.KeyPair

graphics/api.gif
 

java.security.Signature

graphics/api.gif
 

Message Authentication

Suppose you get a message from your friend, signed by your friend with his private key, using the method we just showed you. You may already have his public key, or you can easily get it by asking him for a copy or by getting it from your friend's web page. Then, you can verify that the message was in fact authored by your friend and has not been tampered with. Now, suppose you get a message from a stranger who claims to represent a famous software company, urging you to run the program that is attached to the message. The stranger even sends you a copy of his public key so you can verify that he authored the message. You check that the signature is valid. This proves that the message was signed with the matching private key and that it has not been corrupted.

Be careful: you still have no idea who wrote the message. Anyone could have generated a pair of public and private keys, signed the message with the private key, and sent the signed message and the public key to you. The problem of determining the identity of the sender is called the authentication problem.

The usual way to solve the authentication problem is simple. Suppose the stranger and you have a common acquaintance whom you both trust. Suppose the stranger meets your acquaintance in person and hands over a disk with the public key. Your acquaintance later meets you, assures you that he met the stranger and that the stranger indeed works for the famous software company, and then gives you the disk (see Figure 9-14). That way, your acquaintance vouches for the authenticity of the stranger.

Figure 9-14. Authentication through a trusted intermediary

graphics/09fig14.gif

In fact, your acquaintance does not actually need to meet you. Instead, he can apply his private signature to the stranger's public key file (see Figure 9-15).

Figure 9-15. Authentication through a trusted intermediary's signature

graphics/09fig15.gif

When you get the public key file, you verify the signature of your acquaintance, and because you trust him, you are confident that he did check the stranger's credentials before applying his signature.

However, you may not have a common acquaintance. Some trust models assume that there is always a "chain of trust"—a chain of mutual acquaintances— so that you trust every member of that chain. In practice, of course, that isn't always true. You may trust your acquaintance, Alice, and you know that Alice trusts Bob, but you don't know Bob and aren't sure that you trust him. Other trust models assume that there is a benevolent big brother in whom we all trust. Some companies are working to become such big brothers, such as Verisign, Inc. (www.verisign.com), and, yes, the United States Postal Service.

You will often encounter digital signatures that are signed by one or more entities who will vouch for the authenticity, and you will need to evaluate to what degree you trust the authenticators. You might place a great deal of trust in Verisign, perhaps because you read their ponderous certification practice statements, or because you heard that they require multiple people with black attache cases to come together into a secure chamber whenever new master keys are to be minted.

However, you should have realistic expectations about what is actually being authenticated. Stratton Sclavos, the CEO of Verisign, does not personally meet every individual who has a public key that is authenticated by Verisign. More likely, that individual just filled out a form on a web page (see Figure 9-16).

Figure 9-16. Request for a digital ID

graphics/09fig16.gif

Such a form asks the requestor to specify the name, organization, country, and e-mail address. Typically, the key (or instructions on how to fetch the key) is mailed to that e-mail address. Thus, you can be reasonably assured that the e-mail address is genuine, but the requestor could have filled in any name and organization. With a "class 1" ID from Verisign, that information is not verified. There are more stringent classes of IDs. For example, with a "class 3" ID, Verisign will require an individual requestor to appear before a notary public, and it will check the financial rating of a corporate requestor. Other authenticators will have different procedures. Thus, when you receive an authenticated message, it is important that you understand what, in fact, is being authenticated.

The X.509 Certificate Format

One of the most common formats for signed certificates is the X.509 format. X.509 certificates are widely used by Verisign, Microsoft, Netscape, and many other companies, for signing e-mail messages, authenticating program code, and certifying many other kinds of data. The X.509 standard is part of the X.500 series of recommendations for a directory service by the international telephone standards body, the CCITT. In its simplest form, an X.509 certificate contains the following data:

Thus, the signer guarantees that a certain identity has a particular public key.

Extensions to the basic X.509 format make it possible for the certificates to contain additional information. For more information on the structure of X.509 certificates, see http://www.ietf.cnri.reston.va.us/ids.by.wg/X.509.html. Peter Gutmann's web site (http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt) contains an entertaining and informative description of the many discrepancies in the X.509 format, as it is implemented by different vendors.

The precise structure of X.509 certificates is described in a formal notation, called "abstract syntax notation #1" or ASN.1. Figure 9-17 shows the ASN.1 definition of version 3 of the X.509 format. The exact syntax is not important for us, but, as you can see, ASN.1 gives a precise definition of the structure of a certificate file. The basic encoding rules, or BER, describe precisely how to save this structure in a binary file. That is, BER describes how to encode integers, character strings, bit strings, and constructs such as SEQUENCE, CHOICE, and OPTIONAL.

Figure 9-17. ASN.1 definition of X.509v3
[Certificate  ::=  SEQUENCE  {
        tbsCertificate        TBSCertif icator
        signatureAlgorithm    AlgorithmIdentifier,
        signature             BIT STRING  }

   TBSCertificate  ::=  SEQUENCE  {
        version         [0]   EXPLICIT Version DEFAULT v1,
        SerialNumber          CertificateSerialNumber,
        signature             AlgorithmIdentifier,
        issuer                Name,
        validity              Validity,
        subject               Name,
        subjectPublicKeyInfo  SubjectPublicKeyInfo,
        issuerUniqeID   [1]  IMPLICIT UniqueIdentifier OPTIONAL,
                              -- If present, version must be v2
                                  or v3
        subjectUniquelD [2]  IMPLICIT UniqueIdentifier OPTIONAL,
                              -- If present, version must be v2
                                  or v3
        extensions      [3]  EXPLICIT Extensions OPTIONAL
                              -- If present, version must be v3
        }

   Version  ::=  INTEGER  {  v1{0}, v2{1}, v3{2}  }

   CertificateSerialNumber  ::=  INTEGER

   Validity ::= SEQUENCE {
        notBefore      CertificateValidityDate,
        notAfter       CertificateValidityDate }

   CertificateValidityDate ::= CHOICE {
        utcTime        UTCTime,
        generalTime    GeneralizedTime }

   UniqueIdentifier  ::=  BIT STRING

   SubjectPublicKeylnfo  ::=  SEQUENCE  {
        algorithm             AlgorithmIdentifier,
        subjectPublicKey      BIT STRING  }

   Extensions  ::=  SEQUENCE OF Extension

   Extension   ::=  SEQUENCE  {
        extnID       OBJECT IDENTIFIER
        critical     BOOLEAN DEFAULT FALSE,
        extnValue    OCTET STRING  }

Actually, the BER rules are not unique; there are several ways of specifying some elements. The distinguished encoding rules (DER) remove these ambiguities. For a readable description of the BER encoding format, we recommend A Layman's Guide to a Subset of ASN.1, BER, and DER by Burton S. Kaliski, Jr., available from http://www.rsasecurity.com/rsalabs/pkcs/. You can find the source code for a useful program for dumping BER encoded files at http://www.cs.auckland.ac.nz/~pgut001/dumpasn1.c.

Generating Certificates

The JDK comes with the keytool program, which is a command-line tool to generate and manage a set of certificates. We expect that ultimately the functionality of this tool will be embedded in other, more user-friendly programs. But right now, we will use keytool to show how Alice can sign a document and send it to Bob, and how Bob can verify that the document really was signed by Alice and not an impostor. We do not discuss all of the keytool features—see the JDK documentation for complete information.

The keytool program manages key stores, databases of certificates, and private keys. Each entry in the key store has an alias. Here is how Alice creates a keystore alice.store and generates a key pair with alias alice.

keytool -genkey -keystore alice.store -alias alice

When creating or opening a keystore, you will be prompted for a keystore password. For this example, just use password. If you were to use the keytool-generated keystore for any serious purpose, you would need to choose a good password and safeguard this file—it contains private signature keys.

When generating a key, you will be prompted for the following information:

Enter keystore password:  password
What is your first and last name?
  [Unknown]:  Alice Lee
What is the name of your organizational unit?
  [Unknown]:  Engineering Department
What is the name of your organization?
  [Unknown]:  ACME Software
What is the name of your City or Locality?
  [Unknown]:  Cupertino
What is the name of your State or Province?
  [Unknown]:  California
What is the two-letter country code for this unit?
  [Unknown]:  US
Is <CN=Alice Lee, OU=Engineering Department, O=ACME Software,
L=Cupertino, ST=California, C=US> correct?
  [no]:  Y

NOTE

graphics/note.gif
 

You can find more information on ASN.1 in ASN.1—Communication Between Heterogeneous Systems by Olivier Dubuisson [Academic Press 2000] (http://www.oss.com/asn1/dubuisson.html) and ASN.1 Complete by John Larmouth [Morgan Kaufmann Publishers 1999] (http://www.nokalva.com/asn1/larmouth.html).

The keytool uses X.500 distinguished names, with components Common Name (CN), Organizational Unit (OU), Organization (O), Location (L), State (ST), and Country (C) to identify key owners and certificate issuers.

Finally, you need to specify a key password, or press enter to use the key store password as the key password.

Suppose Alice wants to give her public key to Bob. She needs to export a certificate file:

keytool -export -keystore alice.store -alias alice -file alice.cert

Now Alice can send the certificate to Bob. When Bob receives the certificate, he can print it:

keytool -printcert -file alice.cert

The printout looks like this:

Owner: CN=Alice Lee, OU=Engineering Department, O=ACME Software,
L=Cupertino, ST=California, C=US

Issuer: CN=Alice Lee, OU=Engineering Department, O=ACME Software,
L=Cupertino, ST=California, C=US

Serial number: 38107867

Valid from: Fri Oct 22 07:44:55 PDT 1999 until: Thu Jan 20
06:44:55 PST 2000

Certificate fingerprints:

MD5: 5D:00:0F:95:01:30:B4:FE:18:CE:9A:35:0F:C9:90:DD

SHA1:F8:C2:7C:E2:0B:1F:69:E2:6C:31:9A:F6:35:FA:A3:4F:83:81:6A:6A

This certificate is self-signed. Therefore, Bob cannot use another trusted certificate to check that this certificate is valid. Instead, he can call up Alice and have her read the certificate fingerprint over the phone.

Some certificate issuers publish certificate fingerprints on their web sites. For example, the JRE includes a key store cacerts in the jre/lib/security directory. It contains certificates from Thawte and VeriSign. To list the contents of a keystore, use the -list option:

keytool -list -keystore jre/lib/security/cacerts

The password for this keystore is changeit. One of the certificates in this keystore is

thawtepremiumserverca, Fri Feb 12 12:15:26 PST 1999, trustedCertEntry,
Certificate fingerprint (MD5):
06:9F:69:79:16:66:90:02:1B:8C:8C:A2:C3:07:6F:3A

You can check that your certificate is valid by visiting the Thawte web site at http://www.thawte.com/certs/trustmap.html.

NOTE

graphics/note.gif
 

Of course, this check requires that you trust that your copy of keytool (and the JRE code in rt.jar that the keytool program calls) has not been tampered with. If you are paranoid, you may want to copy the file to another machine (using a trusted file copy program) and check it on that machine with a freshly downloaded copy of the SDK.

Once Bob trusts the certificate, he can import it into his keystore.

keytool -import -keystore bob.store -alias alice -file alice.cert

CAUTION

graphics/caution.gif
 

Never import a certificate into a keystore that you don't fully trust. Once a certificate is added to the keystore, any program that uses the keystore assumes that the certificate can be used to verify signatures.

Now Alice can start sending signed documents to Bob. The jarsigner tool signs and verifies JAR files. Alice simply adds the document to be signed into a JAR file.

jar cvf document.jar document.txt

Then she uses the jarsigner tool to add the signature to the file. She needs to specify the keystore, the JAR file and the alias of the key to use.

jarsigner -keystore alice.store document.jar alice

When Bob receives the file, he uses the -verify option of the jarsigner program.

jarsigner -verify -keystore bob.store document.jar

Bob does not need to specify the key alias. The jarsigner program finds the X.500 name of the key owner in the digital signature and looks for matching certificates in the keystore.

If the JAR file is not corrupted and the signature matches, then the jarsigner program prints

jar verified.

Otherwise, the program displays an error message.

Signing Certificates

In the preceding section, you saw how to use a self-signed certificate to distribute a public key to another party. However, the recipient of the certificate needed to ensure that the certificate was valid by verifying the fingerprint with the issuer. More commonly, a certificate is signed by a trusted intermediary.

The SDK does not contain tools for certificate signing. In this section, you will see how to write a program that signs a certificate with a private key from a keystore. This program is useful in its own right, and it shows you how to write programs that access the contents of certificates and keystores.

Before looking inside the program code, let's see how to put it to use. Suppose Alice wants to send her colleague Cindy a signed message. But Cindy doesn't want to call up everyone who sends her a signature file to verify the signature fingerprint. There needs to be an entity that Cindy trusts to verify signatures. In this example, we will suppose that Cindy trusts the Information Resources Department at ACME Software to perform this service. To simulate this process, you'll need to create an added keystore acmesoft.store. Generate a key and export the self-signed certificate.

keytool -genkey -keystore acmesoft.store -alias acmeroot
keytool -export -alias acmeroot -keystore acmesoft.store
   -file acmeroot.cert

Then add it to Cindy's key store.

keytool -import -alias acmeroot -keystore cindy.store
   -file acmeroot.cert

Cindy still needs to verify the fingerprint of that root certificate, but from now on, she can simply accept all certificates that are signed by it.

For Alice to send messages to Cindy and to everyone else at ACME Software, she needs to bring her certificate to the Information Resources Department and have it signed. However, the keytool program in the JDK does not have this functionality. That is where the certificate signer program in Example 9-14 comes in. The program reads a certificate file and signs it with a private key in a key store. An authorized staff member at ACME Software would verify Alice's identity and generate a signed certificate as follows:

java CertificateSigner -keystore acmesoft.store -alias acmeroot
   -infile alice.cert -outfile alice_signedby_acmeroot.cert

The certificate signer program must have access to the ACME Software keystore, and the staff member must know the keystore password. Clearly this is a sensitive operation.

Now Alice gives the file alice_signedby_acmeroot.cert file to Cindy and to anyone else in ACME Software. Alternatively, ACME Software can simply store the file in a company directory. Remember, this file contains Alice's public key and an assertion by ACME Software that this key really belongs to Alice.

NOTE

graphics/note.gif
 

The keytool program supports a different mechanism for key signing. The -certreq option produces a certificate request in a standard format that can be processed by certificate authorities such as Thawte and Verisign, or local authorities running software such as the Netscape certificate server.

When Cindy imports the signed certificate into her key store, the key store verifies that the key was signed by a trusted root key that is already present in the key store and she is not asked to verify the certificate fingerprint.

CAUTION

graphics/caution.gif
 

This scenario is for illustrative purposes only. The keytool is really not suitable as a tool for end-users. The keytool silently accepts certificates that are signed by a party that it already trusts, and it asks the user to confirm those that it cannot verify. It never rejects a certificate. It is all too easy for a confused user to accept an invalid certificate.

Once Cindy has added the root certificate and the certificates of the people who regularly send her documents, she never has to worry about the keystore again.

Now let us look at the source code of Example 9-14. First, we load the keystore. The getInstance factory method of the KeyStore class creates a keystore instance of the appropriate type. The keytool-generated keystore has a type of "JKS". The provider of this keystore type is "SUN".

KeyStore store = KeyStore.getInstance("JKS", "SUN");

Now, we need to load the keystore data. The load method requires an input stream and a password. Note that the password is specified as a char[] array, not a string. The JVM can keep strings around for a long time before they are garbage collected. Hackers could potentially find these strings, for example, by examining the contents of swap files. But character arrays can be cleared immediately after they are used.

Here is the code for loading the keystore. Note that we fill the password with spaces immediately after use.

InputStream in = . . .;
char[] password = . . .;
store.load(in, password);
Arrays.fill(password, ' ');
in.close();

Next, we use the getKey method to retrieve the private key for signing. The getKey method requires the key alias and key password. Its return type is Key, and we cast it to PrivateKey since we know that the retrieved key is a private key.

char[] keyPassword = . . .;
PrivateKey issuerPrivateKey
   = (PrivateKey)store.getKey(alias, keyPassword);
Arrays.fill(keyPassword, ' ');

Now we are ready to read in the certificate that needs to be signed. The CertificateFactory class can read in certificates from an input stream. First, you need to get a factory of the appropriate type:

CertificateFactory factory
  = CertificateFactory.getInstance("X.509");

Then, call the generateCertificate method with an input stream:

in = new FileInputStream(inname);
X509Certificate inCert
   = (X509Certificate)factory.generateCertificate(in);
in.close();

The return type of the generateCertificate method is the abstract Certificate class that is the superclass of concrete classes such as X509Certificate. Since we know that the input file actually contains an X509Certificate, we use a cast.

CAUTION

graphics/caution.gif
 

There are two types called Certificate: a deprecated interface in the java.security package, and an abstract class in the java.security.cert package, which is the class that you want to use. If you import both the java.security and the java.security.cert package into your program, you need to resolve the ambiguity and explicitly reference the java.security.cert.Certificate class.

The purpose of this program is to sign the bytes in the certificate. You retrieve the bytes with the getTBSCertificate method:

byte[] inCertBytes = inCert.getTBSCertificate();

Next, we need the distinguished name of the issuer, which we will need to insert into the signed certificate. The name is stored in the issuer certificate in the keystore. You fetch certificates from the keystore with the getCertificate method. Since certificates are public information, you only supply the alias, not a password.

X509Certificate issuerCert
   = (X509Certificate)store.getCertificate(alias);

The getCertificate method has return type Certificate, but once again we know that the returned value is actually an X509Certificate. We obtain the issuer identity from the certificate by calling the getSubjectDN method. That method returns an object of some type that implements the Principal interface. Conceptually, a principal is a real-world entity such as a person, organization, or company.

Principal issuer = issuerCert.getSubjectDN();

We also retrieve the name of the signing algorithm.

String issuerSigAlg = issuerCert.getSigAlgName()

Now we must leave the realm of the standard security library. The standard library contains no methods for generating new certificates. Libraries for certificate generation are available from third-party vendors such as RSA Inc. and the Legion of Bouncy Castle (http://www.bouncycastle.org). However, we will use the classes in the sun.security.x509 package. The usual caveats apply. This package might not be supplied by third-party vendors of Java technology, and Sun Microsystems might change the behavior at any time.

The following code segment carries out these steps:

We will not discuss the use of these classes in detail since we do not recommend the use of Sun libraries for production code. A future version of the SDK may contain classes for certificate generation. In the meantime, you may want to rely on third-party libraries or simply use existing certificate generation software.

Example 9-14 CertificateSigner.java
  1. import java.io.*;
  2. import java.security.*;
  3. import java.security.cert.*;
  4. import java.util.*;
  5.
  6. import sun.security.x509.X509CertInfo;
  7. import sun.security.x509.X509CertImpl;
  8. import sun.security.x509.X500Name;
  9. import sun.security.x509.CertificateIssuerName;
 10.
 11. /**
 12.    This program signs a certificate, using the private key of
 13.    another certificate in a keystore.
 14. */
 15. public class CertificateSigner
 16. {
 17.    public static void main(String[] args)
 18.    {
 19.       String ksname = null; // the keystore name
 20.       String alias = null; // the private key alias
 21.       String inname = null; // the input file name
 22.       String outname = null; // the output file name
 23.       for (int i = 0; i < args.length; i += 2)
 24.       {
 25.          if (args[i].equals("-keystore"))
 26.             ksname = args[i + 1];
 27.          else if (args[i].equals("-alias"))
 28.             alias = args[i + 1];
 29.          else if (args[i].equals("-infile"))
 30.             inname = args[i + 1];
 31.          else if (args[i].equals("-outfile"))
 32.             outname = args[i + 1];
 33.          else usage();
 34.       }
 35.
 36.       if (ksname == null || alias == null ||
 37.          inname == null || outname == null) usage();
 38.
 39.       try
 40.       {
 41.          PushbackReader console = new PushbackReader(new
 42.             InputStreamReader(System.in));
 43.
 44.          KeyStore store = KeyStore.getInstance("JKS", "SUN");
 45.          InputStream in = new FileInputStream(ksname);
 46.          System.out.print("Keystore password: ");
 47.          System.out.flush();
 48.          char[] password = readPassword(console);
 49.          store.load(in, password);
 50.          Arrays.fill(password, ' ');
 51.          in.close();
 52.
 53.          System.out.print("Key password for " + alias + ": ");
 54.          System.out.flush();
 55.          char[] keyPassword = readPassword(console);
 56.          PrivateKey issuerPrivateKey
 57.             = (PrivateKey)store.getKey(alias, keyPassword);
 58.          Arrays.fill(keyPassword, ' ');
 59.
 60.          if (issuerPrivateKey == null)
 61.             error("No such private key");
 62.
 63.          in = new FileInputStream(inname);
 64.
 65.          CertificateFactory factory
 66.             = CertificateFactory.getInstance("X.509");
 67.
 68.          X509Certificate inCert
 69.             = (X509Certificate)factory.generateCertificate(in);
 70.          in.close();
 71.          byte[] inCertBytes = inCert.getTBSCertificate();
 72.
 73.          X509Certificate issuerCert
 74.             = (X509Certificate)store.getCertificate(alias);
 75.          Principal issuer = issuerCert.getSubjectDN();
 76.          String issuerSigAlg = issuerCert.getSigAlgName();
 77.
 78.          FileOutputStream out = new FileOutputStream(outname);
 79.
 80.          X509CertInfo info = new X509CertInfo(inCertBytes);
 81.          info.set(X509CertInfo.ISSUER,
 82.             new CertificateIssuerName((X500Name)issuer));
 83.
 84.          X509CertImpl outCert = new X509CertImpl(info);
 85.          outCert.sign(issuerPrivateKey, issuerSigAlg);
 86.          outCert.derEncode(out);
 87.
 88.          out.close();
 89.       }
 90.       catch (Exception exception)
 91.       {
 92.          exception.printStackTrace();
 93.       }
 94.    }
 95.
 96.    /**
 97.       Reads a password.
 98.       @param in the reader from which to read the password
 99.       @return an array of characters containing the password
100.    */
101.    public static char[] readPassword(PushbackReader in)
102.       throws IOException
103.    {
104.       final int MAX_PASSWORD_LENGTH = 100;
105.       int length = 0;
106.       char[] buffer = new char[MAX_PASSWORD_LENGTH];
107.
108.       while (true)
109.       {
110.          int ch = in.read();
111.          if (ch == '\r' || ch == '\n' || ch == -1
112.             || length == MAX_PASSWORD_LENGTH)
113.          {
114.             if (ch == '\r') // handle DOS "\r\n" line ends
115.             {
116.                ch = in.read();
117.                if (ch != '\n' && ch != -1) in.unread(ch);
118.             }
119.             char[] password = new char[length];
120.             System.arraycopy(buffer, 0, password, 0, length);
121.             Arrays.fill(buffer, ' ');
122.             return password;
123.          }
124.          else
125.          {
126.             buffer[length] = (char)ch;
127.             length++;
128.          }
129.       }
130.    }
131.
132.    /**
133.       Prints an error message and exits.
134.       @param message
135.    */
136.    public static void error(String message)
137.    {
138.       System.out.println(message);
139.       System.exit(1);
140.    }
141.
142.    /**
143.       Prints a usage message and exits.
144.    */
145.    public static void usage()
146.    {
147.       System.out.println("Usage: java CertificateSigner"
148.          + " -keystore keyStore -alias issuerKeyAlias"
149.          + " -infile inputFile -outfile outputFile");
150.       System.exit(1);
151.    }
152. }
java.security.KeyStore

graphics/api.gif
 

java.security.cert.CertificateFactory

graphics/api.gif
 

java.security.cert.Certificate

graphics/api.gif
 

java.security.cert.X509Certificate

graphics/api.gif
 

Code Signing

One of the most important uses of authentication technology is signing executable programs. If you download a program, you are naturally concerned about damage that a program can do. For example, the program could have been infected by a virus. If you know where the code comes from and that it has not been tampered with since it left its origin, then your comfort level will be a lot higher than without this knowledge. In fact, if the program was also written in the Java programming language, you can then use this information to make a rational decision about what privileges you will allow that program to have. You might just want it to run in a sandbox as a regular applet, or you might want to grant it a different set of rights and restrictions. For example, if you download a word processing program, you might want to grant it access to your printer and to files in a certain subdirectory. But you may not want to give it the right to make network connections, so that the program can't try to send your files to a third party without your knowledge.

You now know how to implement this sophisticated scheme.

  1. First, use authentication to verify where the code came from.

  2. Then, run the code with a security policy that enforces the permissions that you want to grant the program, depending on its origin.

Signing JAR Files

At this point, code signing is still somewhat platform dependent. If you use JDK 1.1 applets with Netscape or Internet Explorer, you need to use the Netscape or Microsoft tools to sign your applets. See www.securingjava.com/appdx-c/ or www.suitable.com/Doc_CodeSigning.shtml for more information on this topic.

In this section, we show you how to sign applets for use with the Java Plug-In software. There are two scenarios:

  1. Signed intranet applets;

  2. Signed Internet applets.

In the first scenario, a system administrator installs certificates and policy files on local machines. Whenever the Java Plug-in loads a signed applet, it consults the keystore for signatures and the policy file for the applet permissions. Installing the certificates and policies is straightforward and can be done once per desktop. End users can then run signed corporate applets outside the sandbox. Whenever a new applet is created or an existing applet is updated, it must be signed and deployed on the web server. However, no desktops need to be touched as the applets evolve. We think this is a reasonable scenario that can be an attractive alternative over deploying corporate applications on every desktop.

In the second scenario, software vendors obtain certificates that are signed by certificate authorities such as Thawte and Verisign. When an end user visits a web site that contains a signed applet, a dialog pops up that identifies the software vendor and gives the end user two choices: to run the applet with full privileges, or to confine it to the sandbox. We discuss this scenario in detail later.

For the remainder of this section, we describe how you can build policy files that grant specific permissions to applets from known sources. Building and deploying these policy files is not for casual end users. However, system administrators can carry out these tasks in preparation for distributing intranet applets.

Suppose ACME Software wants its users to run certain applets that require local file access. Since these applets cannot run inside the sandbox, ACME Software needs to install policy files on employee machines. As you saw earlier in this chapter, ACME could identify the applets by their code base. But that means that ACME would need to update the policy files each time the applet code is moved to a different web server. Instead, ACME decides to sign the JAR files that contain the applet code.

To make a signed JAR file, first add your class files to a JAR file.

jar cvf MyApplet.jar *.class

Then run the jarsigner tool and specify the JAR file and the alias of the private key:

jarsigner -keystore acmesoft.store MyApplet.jar acmeroot

In this example, the JAR file is signed with the self-signed root key. In practice, it would be more likely that ACME issues its programmers individual keys that are themselves signed by the root key.

Of course, the keystore containing the root key must be kept at a safe place. Let's make a second keystore certs.store for certificates and add the acmeroot certificate into it.

keytool -export -keystore acmesoft.store -alias acmeroot -file
   acmeroot.cert
keytool -import -keystore certs.store -alias acmeroot -file
   acmeroot.cert

Next, you need to create a policy file that gives the permission for all applets that are signed with signatures in that keystore.

You need to include the location of your keystore in the policy file. Add a line

keystore "keystoreURL", "keystoreType";

to the top of the policy file. The type is JKS if the keystore was generated by keytool.

keystore "file:certs.store", "JKS";

Then add signedBy "alias" to one or more grant clauses in the policy file. For example,

grant signedBy "acmeroot"
{
   permission java.io.FilePermission "<<ALL FILES>>", "read";
   . . .
};

Any signed code that can be verified with the public key associated with the alias is now granted these permissions.

You can try this out with the applet in Example 9-15. The applet tries to read from a local file (see Figure 9-18). The default security policy lets the applet read files from its code base and any subdirectories. Use appletviewer to run the applet and verify that you can view files from the code base directory, but not from other directories.

Figure 9-18. The FileReadApplet program

graphics/09fig18.gif
 

Now place the applet in a JAR file and sign it with the acmeroot key. Then create a policy file applets.policy with the contents:

keystore "file:certs.store", "JKS";
grant signedBy "acmeroot"
{
     permission java.io.FilePermission "<<ALL FILES>>", "read";
};

NOTE

graphics/note.gif
 

You can also use the policytool to create the policy file.

For this test, make sure that the keystore, policy file, and JAR file are all in the same directory.

Finally, tell the appletviewer to use the policy file:

appletviewer -J-Djava.security.policy=applets.policy
   FileReadApplet.html

Now the applet can read all files.

This shows that the signing mechanism works. To actually deploy this mechanism, you need to find appropriate places for the security files. We take up that topic in the next section.

As a final test, you may want to test your applet inside the Java Plug-In tool. Then, you need to modify the file java.security in the jre/lib/security directory. Locate the section

# The default is to have a single system wide policy file,
# and a policy file in the user's home directory.
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy

Add a line with a file URL for the policy file, such as

policy.url.3=file:///home/test/applet.policy

CAUTION

graphics/caution.gif
 

Be sure to modify the correct java.security file. The Java Plug-In software uses the virtual machine in the JRE, not the one belonging to the JDK. In particular, under Windows, the JRE files are located inside the \Program Files\JavaSoft directory.

If you use the Java Plug-In software in Netscape 4 or Internet Explorer, you also need to change the HTML file to load the plug-in with an EMBED or OBJECT tag. Opera and Netscape 6 automatically load the Java Plug-In software when you use the APPLET tag. (See Chapter 10 of Volume 1 for more information on how to load the Java Plug-In tool.)

CAUTION

graphics/caution.gif
 

If you test your applet with the Java Plug-In instead of the appletviewer, then you need to be aware that the plug-in only reads the policy file once, when it is loaded for the first time. If you made a mistake in your policy file or keystore, then you need to close down the browser, fix your mistake, and restart the browser. Simply reloading the web page containing the applet does not work.

Example 9-15 FileReadApplet.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.io.*;
 4. import java.util.*;
 5. import javax.swing.*;
 6.
 7. /**
 8.    This applet can run "outside the sandbox" and
 9.    read local files when it is given the right permissions.
10. */
11. public class FileReadApplet extends JApplet
12. {
13.    public FileReadApplet()
14.    {
15.       fileNameField = new JTextField(20);
16.       JPanel panel = new JPanel();
17.       panel.add(new JLabel("File name:"));
18.       panel.add(fileNameField);
19.       JButton openButton = new JButton("Open");
20.       panel.add(openButton);
21.       openButton.addActionListener(new
22.          ActionListener()
23.          {
24.             public void actionPerformed(ActionEvent event)
25.             {
26.                loadFile(fileNameField.getText());
27.             }
28.          });
29.
30.       Container contentPane = getContentPane();
31.       contentPane.add(panel, "North");
32.
33.       fileText = new JTextArea();
34.       contentPane.add(new JScrollPane(fileText), "Center");
35.    }
36.
37.    /**
38.       Loads the contents of a file into the text area.
39.       @param filename the file name
40.    */
41.    public void loadFile(String filename)
42.    {
43.       try
44.       {  fileText.setText("");
45.          BufferedReader in
46.             = new BufferedReader(new FileReader(filename));
47.          String s;
48.          while ((s = in.readLine()) != null)
49.          fileText.append(s + "\n");
50.          in.close();
51.       }
52.       catch (IOException e)
53.       {
54.          fileText.append(e + "\n");
55.       }
56.       catch (SecurityException e)
57.       {
58.          fileText.append("I am sorry, but I cannot do that.");
59.       }
60.    }
61.
62.    private JTextField fileNameField;
63.    private JTextArea fileText;
64. }

Deployment Tips

The first decision you need to make is where to deploy policy files. There are two default locations:

We don't think either is a good choice. Instead, we recommend that you edit the java.security file in the ${java.home}/jre/lib/security directory and add a line to include a third policy file, such as:

policy.url.3=http://intranet.acmesoft.com/admin/applet.policy

Then, you can set up a policy file on an intranet server. That is an advantage since you only need to manage a file in a single location.

Similarly, inside the policy file, you can specify the keystore location with an URL:

keystore "http://intranet.acmesoft.com/admin/certs.store", "JKS";

Add the certificate for the public key for corporate intranet applications to that keystore.

NOTE

graphics/note.gif
 

You could add certificates to the cacerts keystore in the JRE. But then you would need to keep updating the JRE on every desktop when you change the keystore. We recommend that you don't touch the cacerts file.

Finally, sign the JAR files that contain the code for your intranet applications with the matching private key.

We suggest that you don't simply grant AllPermission to intranet applets, but that you augment the "sandbox" rights by specific privileges, such as accessing all directories inside a particular subdirectory, printing, network access within the intranet, and so on.

The deployment sounds a bit complex, but it is actually quite manageable. You need to minimally customize the Java Plug-In configuration on each desktop. The rest can be managed remotely. There are two benefits. At no time do you place a burden on your users to make solitary security decisions. And you have fine-grained control over the privileges of the remote code that your users execute.

NOTE

graphics/note.gif
 

Because Java platform security combines authentication and control over code permissions, it offers a far more comprehensive security model than does Microsoft's ActiveX technology. ActiveX code is authenticated, but once it gains permission to run, it cannot be controlled at all.

Software Developer Certificates

Up to now, we discussed scenarios where applets are delivered in an intranet and a system administrator configures a security policy that controls the privileges of the applets. However, that strategy only works with applets from known sources.

Suppose you surf the Internet and you encounter a web site that offers to run an applet from an unfamiliar vendor, provided you grant it the permission to do so (see Figure 9-19). Such an applet is signed with a software developer certificate that is issued by a certificate authority such as Verisign. The pop-up dialog identifies the software developer and the certificate issuer. You now have two choices:

Figure 9-19. Launching a signed applet

graphics/09fig19.gif
 

What facts do you have at your disposal that might influence your decision? Here is what you know:

  1. Thawte sold a certificate to the software developer.

  2. The applet really was signed with that certificate, and it hasn't been modified in transit.

  3. The certificate really was signed by Thawte—it was verified by the public key in the local cacerts file.

Does that tell you whether the code is safe to run? Do you trust the vendor if all you know is the vendor name (*.netbizz.dk) and the fact that Thawte sold them a software developer certificate? Presumably Thawte went to some degree of trouble to assure itself that *.netbizz.dk is not an outright cracker.

However, no certificate issuer carries out a comprehensive audit of the honesty and competence of software vendors.

In the situation of an unknown vendor, an end user is ill-equipped to make an intelligent decision whether to let this applet run outside the sandbox, with all permissions of a local application. If the vendor is a well-known company, then the user can at least take the past track record of the company into account.

We don't like situations where a program demands "give me all rights, or I won't run at all." Naïve users are too often cowed into granting access that can put them into danger. Would it help if the applet explained what rights it needs and seeks specific permission for those rights? Unfortunately, as you have seen, that can get pretty technical. It doesn't seem reasonable for an end user to have to ponder whether an applet should really have the right to inspect the AWT event queue. Perhaps, a future version of a plug-in can define permission sets that are meaningful to an end user. Until that time, we remain unenthusiastic about applets that are signed with software developer certificates.

If you want to deploy your applets to the world at large and you think that your users trust you enough that they will allow your applets to run with full permissions on their machine, then you may want to purchase a certificate from Thawte or Verisign and use it to sign your applets. See http://java.sun.com/products/plugin/1.2/docs/nsobjsigning.html for more information.

Encryption

So far, we have discussed one important cryptographic technique that is implemented in the Java security API, namely authentication through digital signatures. A second important aspect of security is encryption. When information is authenticated, the information itself is plainly visible. The digital signature merely verifies that the information has not been changed. In contrast, when information is encrypted, it is not visible. It can only be decrypted with a matching key.

Authentication is sufficient for code signing—there is no need for hiding the code. But encryption is necessary when applets or applications transfer confidential information, such as credit card numbers and other personal data.

Until recently, patents and export controls have prevented many companies, including Sun, from offering strong encryption. Fortunately, export controls are now much less stringent, and the patent for the RSA algorithm finally expired in October 2000. As of SDK 1.4, good encryption support is part of the standard library. Crypto support is also available as a separate extension (called JCE) for older versions of the SDK.

Symmetric Ciphers

The Java cryptographic extensions contain a class Cipher which is the superclass for all encryption algorithms. You get a cipher object by calling the getInstance method:

Cipher cipher = Cipher.getInstance(algorithName);

or

Cipher cipher = Cipher.getInstance(algorithName, providerName);

The SDK comes with ciphers by the provider named "SunJCE". That is the default provider that is used if you don't specify another provider name. You will see in the next section how to add other providers.

The algorithm name is a string such as "DES" or "DES/CBC/PKCS5Padding".

DES, the Data Encryption Standard, is a venerable block cipher with a key length of 56 bits. Nowadays, the DES algorithm is considered obsolete because it has become possible to crack it with brute force (see, for example, http://www.eff.org/descracker/). A far better alternative is its successor, the Advanced Encryption Standard (AES). See http://csrc.nist.gov/encryption/aes/ for more information on AES. At the time of this writing, the SunJCE provider supports DES but not AES.

Once you have a cipher object, you initialize it by setting the mode and the key.

int mode = . . .;
Key key = . . .;
cipher.init(mode, key);

The mode is one of

Cipher.ENCRYPT_MODE
Cipher.DECRYPT_MODE
Cipher.WRAP_MODE
Cipher.UNWRAP_MODE

The wrap and unwrap modes are used to encrypt one key with another—see the next section for an example.

Now you can repeatedly call the update method to encrypt blocks of data:

int blockSize = cipher.blockSize();
byte[] inBytes = new byte[blockSize];
. . . // read inBytes
int outputSize = cipher.outputSize(inLength);
byte[] outBytes = new byte[outputSize];
int outLength = cipher.update(inBytes, 0, outputSize, outBytes);
. . . // write outBytes

When you are done, you must call the doFinal method once. If there is a final block of input data available (with fewer than blockSize bytes), then call

outBytes = cipher.doFinal(inBytes, 0, inLength);

If all input data have been encrypted, call

outBytes = cipher.doFinal();

instead.

The call to doFinal is necessary to carry out padding of the final block. Consider the DES cipher. It has a block size of 8 bytes. Suppose the last block of the input data has less than 8 bytes. Of course, we can fill the remaining bytes with 0, to obtain one final block of 8 bytes, and encrypt it. But when decrypting, the result will have several trailing 0 bytes appended to it, and therefore it will be slightly different from the original input file. That may well be a problem, and a padding scheme is needed to avoid it. A commonly used padding scheme is the one described in the Public Key Cryptography Standard (PKCS) #5 by RSA Security Inc. (http://www.rsasecurity.com/rsalabs/pkcs/pkcs-5). In this scheme, the last block is not padded with a pad value of zero, but with a pad value that equals the number of pad bytes. In other words, if L is the last (incomplete) block, then it is padded as follows:

L 01                     if length(L) = 7
L 02 02                  if length(L) = 6
L 03 03 03               if length(L) = 5
. . .
L 07 07 07 07 07 07 07   if length(L) = 1

Finally, if the length of the input is actually divisible by 8, then one block

08 08 08 08 08 08 08 08

is appended to the input and decrypted. When decrypting, the very last byte of the plaintext is a count of the padding characters to discard.

Finally, we need to explain how to obtain a key. You can generate a completely random key by following these steps.

  1. Get a KeyGenerator for your algorithm.

  2. Initialize the generator with a source for randomness. If the block length of the cipher is variable, you also need to specify the desired block length.

  3. Call the generateKey method.

For example, here is how you generate a DES key.

KeyGenerator keygen = KeyGenerator.getInstance("DES");
SecureRandom random = new SecureRandom();
keygen.init(random);
Key key = keygen.generateKey();

Alternatively, you may want to produce a key from a fixed set of raw data (perhaps derived from a password or the timing of keystrokes). Then use a SecretKeyFactory like this:

SecretKeyFactory keyFactory
   = SecretKeyFactory.getInstance("DES");
byte[] keyData = . . .; // 8 bytes for DES
SecretKeySpec keySpec = new SecretKeySpec(keyData, "DES");
Key key = keyFactory.generateSecret(keySpec);

The sample program at the end of this section puts the DES cipher to work (see Example 9-16). To use the program, you first need to generate a secret key. Run

java DESTest -genkey secret.key

The secret key is saved in the file secret.key

Now you can encrypt with the command

java DESTest -encrypt plaintextFile encryptedFile secret.key

Decrypt with the command

java DESTest -decrypt encryptedFile decryptedFile secret.key

The program is straightforward. The -genkey option produces a new secret key and serializes it in the given file. That operation takes a long time because the initialization of the secure random generator is time consuming. The -encrypt and -decrypt options both call into the same crypt method that calls the update and doFinal methods of the cipher. Note how the update method is called as long as the input blocks have the full length, and the doFinal method is either called with a partial input block (which is then padded) or with no additional data (to generate one pad byte).

Example 9-16 DESTest.java
  1. import java.io.*;
  2. import java.security.*;
  3. import javax.crypto.*;
  4. import javax.crypto.spec.*;
  5.
  6. /**
  7.    This program tests the DES cipher. Usage:
  8.    java DESTest -genkey keyfile
  9.    java DESTest -encrypt plaintext encrypted keyfile
 10.    java DESTest -decrypt encrypted decrypted keyfile
 11. */
 12. public class DESTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       try
 17.       {
 18.          if (args[0].equals("-genkey"))
 19.          {
 20.             KeyGenerator keygen
 21.                = KeyGenerator.getInstance("DES");
 22.             SecureRandom random = new SecureRandom();
 23.             keygen.init(random);
 24.             SecretKey key = keygen.generateKey();
 25.             ObjectOutputStream out = new ObjectOutputStream(
 26.                new FileOutputStream(args[1]));
 27.             out.writeObject(key);
 28.             out.close();
 29.          }
 30.          else
 31.          {
 32.             int mode;
 33.             if (args[0].equals("-encrypt"))
 34.                mode = Cipher.ENCRYPT_MODE;
 35.             else
 36.                mode = Cipher.DECRYPT_MODE;
 37.
 38.             ObjectInputStream keyIn = new ObjectInputStream(
 39.                new FileInputStream(args[3]));
 40.             Key key = (Key) keyIn.readObject();
 41.             keyIn.close();
 42.
 43.             InputStream in = new FileInputStream(args[1]);
 44.             OutputStream out = new FileOutputStream(args[2]);
 45.             Cipher cipher = Cipher.getInstance("DES");
 46.             cipher.init(mode, key);
 47.
 48.             crypt(in, out, cipher);
 49.             in.close();
 50.             out.close();
 51.          }
 52.       }
 53.       catch (IOException exception)
 54.       {
 55.          exception.printStackTrace();
 56.       }
 57.       catch (GeneralSecurityException exception)
 58.       {
 59.          exception.printStackTrace();
 60.       }
 61.       catch (ClassNotFoundException exception)
 62.       {
 63.          exception.printStackTrace();
 64.       }
 65.    }
 66.
 67.    /**
 68.       Uses a cipher to transform the bytes in an input stream
 69.       and sends the transformed bytes to an output stream.
 70.       @param in the input stream
 71.       @param out the output stream
 72.       @param cipher the cipher that transforms the bytes
 73.    */
 74.    public static void crypt(InputStream in, OutputStream out,
 75.       Cipher cipher) throws IOException, GeneralSecurityException
 76.    {
 77.       int blockSize = cipher.getBlockSize();
 78.       int outputSize = cipher.getOutputSize(blockSize);
 79.       byte[] inBytes = new byte[blockSize];
 80.       byte[] outBytes = new byte[outputSize];
 81.
 82.       int inLength = 0;;
 83.       boolean more = true;
 84.       while (more)
 85.       {
 86.          inLength = in.read(inBytes);
 87.          if (inLength == blockSize)
 88.          {
 89.             int outLength
 90.                = cipher.update(inBytes, 0, blockSize, outBytes);
 91.             out.write(outBytes, 0, outLength);
 92.             System.out.println(outLength);
 93.          }
 94.          else more = false;
 95.       }
 96.       if (inLength > 0)
 97.          outBytes = cipher.doFinal(inBytes, 0, inLength);
 98.       else
 99.          outBytes = cipher.doFinal();
100.       System.out.println(outBytes.length);
101.       out.write(outBytes);
102.    }
103. }
java.security.Cipher

graphics/api.gif
 

java.security.KeyGenerator

graphics/api.gif
 

javax.crypto.SecretKeyFactory

graphics/api.gif
 

javax.crypto.spec.SecretKeySpec

graphics/api.gif
 

Public Key Ciphers

The DES cipher that you have seen in the preceding section is a symmetric cipher. The same key is used for encryption and for decryption. The Achilles heel of symmetric ciphers is key distribution. If Alice sends Bob an encrypted method, then Bob needs the same key that Alice used. If Alice changes the key, then she needs to send Bob both the message, and, through a secure channel, the new key. But perhaps she has no secure channel to Bob, which is why she encrypts her messages to him in the first place.

Public key cryptography solves that problem. In a public key cipher, Bob has a key pair consisting of a public key and a matching private key. Bob can publish the public key anywhere, but he must closely guard the private key. Alice simply uses the public key to encrypt her messages to Bob.

Actually, it's not quite that simple. All known public key algorithms are much slower than symmetric key algorithms such as DES or AES. It would not be practical to use a public key algorithm to encrypt large amounts of information. But that problem can be overcome easily by combining a public key cipher with a fast symmetric cipher, like this:

  1. Alice generates a random symmetric encryption key. She uses it to encrypt her plaintext.

  2. Alice encrypts the symmetric key with Bob's public key.

  3. Alice sends Bob both the encrypted symmetric key and the encrypted plaintext.

  4. Bob uses his private key to decrypt the symmetric key.

  5. Bob uses the decrypted symmetric key to decrypt the message.

Nobody but Bob can decrypt the symmetric key because only Bob has the private key for decryption. Thus, the expensive public key encryption is only applied to a small amount of key data.

The most commonly used public key algorithm is the RSA algorithm invented by Rivest, Shamir, and Adleman. Until October 2000, the algorithm was protected by a patent assigned to RSA Security Inc. Licenses were not cheap—typically a 3% royalty, with a minimum payment of $50,000 per year. Now the algorithm is in the public domain. Unfortunately, the SunJCE provider does not expose an RSA algorithm object, even though there is an RSA implementation within the SDK.

We found another provider, the "Legion of Bouncy Castle," which supports RSA as well as a number of other features missing from the SunJCE provider. Most importantly, the JAR file with the provider code has been signed by Sun Microsystems so that you can combine it with the JCE implementation of the SDK. (If an algorithm provider's code is not signed by Sun, you need to use an alternate "cleanroom" implementation of the JCE, not the one that is part of the SDK.) To test out the next sample program, you need to download the provider JAR file from http://www.bouncycastle.org/index.html.

There are two ways for installing a new provider. You can add a line to the security description file, jre/lib/security/java.security. By default, there are already several providers. To add a new provider, add a line such as

security.provider.6=org.bouncycastle.jce.provider
   .BouncyCastleProvider

Or you can dynamically load another security provider with the addProvider method of the Security class:

Security.addProvider(new BouncyCastleProvider());

In either case, you must make sure that the provider code is accessible. You can just move the JAR file into the jre/lib/ext directory, or you can add it to the class path.

To use the RSA algorithm, you need a public/private key pair. You use a KeyPairGenerator like this:

KeyPairGenerator pairgen
   = KeyPairGenerator.getInstance("RSA", "BC");
  SecureRandom random = new SecureRandom();
  pairgen.initialize(KEYSIZE, random);
  KeyPair keyPair = pairgen.generateKeyPair();
  Key publicKey = keyPair.getPublic();
  Key privateKey = keyPair.getPrivate();

The program in Example 9-17 has three options. The -genkey option produces a key pair. The -encrypt option generates a DES key and wraps it with the public key.

Key key = . . .; // a DES key
Key publicKey = . . .; // a public RSA key
Cipher cipher = Cipher.getInstance("RSA", "BC");
cipher.init(Cipher.WRAP_MODE, publicKey);
byte[] wrappedKey = cipher.wrap(key);

It then produces a file that contains

The -decrypt option decrypts such a file. To try out the program, first generate the RSA keys:

java RSATest -genkey public.key private.key

Then encrypt a file

java RSATest -encrypt plaintextFile encryptedFile public.key

Finally, decrypt it and verify that the decrypted file matches the plain text.

java RSATest -decrypt encryptedFile decryptedFile private.key

NOTE

graphics/note.gif
 

Before running this program, make sure you follow the instructions at the beginning of this section for installing the "Bouncy Castle" provider. Either edit the java.security file or edit the program and add a call to load the provider. Place the provider JAR file into the extensions directory or add it to the class path.

Example 9-17 RSATest.java
  1. import java.io.*;
  2. import java.security.*;
  3. import javax.crypto.*;
  4. import javax.crypto.spec.*;
  5.
  6. /**
  7.    This program tests the RSA cipher. Usage:
  8.    java RSATest -genkey public private
  9.    java RSATest -encrypt plaintext encrypted public
 10.    java RSATest -decrypt encrypted decrypted private
 11. */
 12. public class RSATest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       try
 17.       {
 18.          if (args[0].equals("-genkey"))
 19.          {
 20.             KeyPairGenerator pairgen
 21.                = KeyPairGenerator.getInstance("RSA", "BC");
 22.             SecureRandom random = new SecureRandom();
 23.             pairgen.initialize(KEYSIZE, random);
 24.             KeyPair keyPair = pairgen.generateKeyPair();
 25.             ObjectOutputStream out = new ObjectOutputStream(
 26.                new FileOutputStream(args[1]));
 27.             out.writeObject(keyPair.getPublic());
 28.             out.close();
 29.             out = new ObjectOutputStream(
 30.                new FileOutputStream(args[2]));
 31.             out.writeObject(keyPair.getPrivate());
 32.             out.close();
 33.          }
 34.          else if (args[0].equals("-encrypt"))
 35.          {
 36.             KeyGenerator keygen
 37.                = KeyGenerator.getInstance("DES");
 38.             SecureRandom random = new SecureRandom();
 39.             keygen.init(random);
 40.             SecretKey key = keygen.generateKey();
 41.
 42.             // wrap with RSA public key
 43.             ObjectInputStream keyIn = new ObjectInputStream(
 44.                new FileInputStream(args[3]));
 45.             Key publicKey = (Key) keyIn.readObject();
 46.             keyIn.close();
 47.
 48.             Cipher cipher = Cipher.getInstance("RSA", "BC");
 49.             cipher.init(Cipher.WRAP_MODE, publicKey);
 50.             byte[] wrappedKey = cipher.wrap(key);
 51.             DataOutputStream out = new DataOutputStream(new
 52.                FileOutputStream(args[2]));
 53.             out.writeInt(wrappedKey.length);
 54.             out.write(wrappedKey);
 55.
 56.             InputStream in = new FileInputStream(args[1]);
 57.             cipher = Cipher.getInstance("DES", "BC");
 58.             cipher.init(Cipher.ENCRYPT_MODE, key);
 59.             crypt(in, out, cipher);
 60.             in.close();
 61.             out.close();
 62.          }
 63.          else
 64.          {
 65.             DataInputStream in = new DataInputStream(new
 66.                FileInputStream(args[1]));
 67.             int length = in.readInt();
 68.             byte[] wrappedKey = new byte[length];
 69.             in.read(wrappedKey, 0, length);
 70.
 71.             // unwrap with RSA private key
 72.             ObjectInputStream keyIn = new ObjectInputStream(
 73.                new FileInputStream(args[3]));
 74.             Key privateKey = (Key) keyIn.readObject();
 75.             keyIn.close();
 76.
 77.             Cipher cipher = Cipher.getInstance("RSA", "BC");
 78.             cipher.init(Cipher.UNWRAP_MODE, privateKey);
 79.             Key key = cipher.unwrap(wrappedKey, "DES",
 80.                Cipher.SECRET_KEY);
 81.
 82.             OutputStream out = new FileOutputStream(args[2]);
 83.             cipher = Cipher.getInstance("DES", "BC");
 84.             cipher.init(Cipher.DECRYPT_MODE, key);
 85.
 86.             crypt(in, out, cipher);
 87.             in.close();
 88.             out.close();
 89.          }
 90.       }
 91.       catch (IOException exception)
 92.       {
 93.          exception.printStackTrace();
 94.       }
 95.       catch (GeneralSecurityException exception)
 96.       {
 97.          exception.printStackTrace();
 98.       }
 99.       catch (ClassNotFoundException exception)
100.       {
101.          exception.printStackTrace();
102.       }
103.    }
104.
105.    /**
106.       Uses a cipher to transform the bytes in an input stream
107.       and sends the transformed bytes to an output stream.
108.       @param in the input stream
109.       @param out the output stream
110.       @param cipher the cipher that transforms the bytes
111.    */
112.    public static void crypt(InputStream in, OutputStream out,
113.       Cipher cipher) throws IOException, GeneralSecurityException
114.    {
115.       int blockSize = cipher.getBlockSize();
116.       int outputSize = cipher.getOutputSize(blockSize);
117.       byte[] inBytes = new byte[blockSize];
118.       byte[] outBytes = new byte[outputSize];
119.
120.       int inLength = 0;;
121.       boolean more = true;
122.       while (more)
123.       {
124.          inLength = in.read(inBytes);
125.          if (inLength == blockSize)
126.          {
127.             int outLength
128.                = cipher.update(inBytes, 0, blockSize, outBytes);
129.             out.write(outBytes, 0, outLength);
130.          }
131.          else more = false;
132.       }
133.       if (inLength > 0)
134.          outBytes = cipher.doFinal(inBytes, 0, inLength);
135.       else
136.          outBytes = cipher.doFinal();
137.       out.write(outBytes);
138.    }
139.
140.    public static final int KEYSIZE = 128;
141. }
java.security.Security

graphics/api.gif
 

Cipher Streams

The JCE library provides a convenient set of stream classes that automatically encrypt or decrypt stream data. For example, here is how you can encrypt data to a file:

Cipher cipher = . . .;
cipher.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream out = new CipherOutputStream(
   new FileOutputStream(outputFileName), cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = getData(bytes); // get data from data source
while (inLength != -1)
{
   out.write(bytes, 0, inLength);
   inLength = getData(bytes); // get more data from data source
}
out.flush();

Similarly, you can use a CipherInputStream to read and decrypt data from a file:

Cipher cipher = . . .;
cipher.init(Cipher.DECRYPT_MODE, key);
CipherInputStream in = new CipherInputStream(
   new FileInputStream(inputFileName), cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = in.read(bytes);
while (inLength != -1)
{
   putData(bytes, inLength); // put data to destination
   inLength = in.read(bytes);
}

The cipher stream classes transparently handle the calls to update and doFinal, which is clearly a convenience.

javax.security.CipherInputStream

graphics/api.gif
 

javax.security.CipherOutputStream

graphics/api.gif
 

CONTENTS